I am building a simple react app to interface with the DHIS2 web api. Previously in my app, I sent GET requests using my credentials to authenticate my requests. Now I want to sign in a user, or get the currently authenticated user using the Auth2.0 request, I keep getting the CORS error, even though localhost:3000 is whitelisted on our dhis2 instance. Also I can make GET requests for programs, dataElements etc without problems, but the Auth2.0 request brings the CORS error. Any idea on how to solve it?
Here’s the error : Access to fetch at 'http://covmw.com/namistest/dhis-web-commons/security/login.action' (redirected from 'https://covmw.com/namistest/uaa/oauth/token/') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
Actually, this should be fine. As @itwabi noticed other API endpoints work fine with CORS and a localhost client (this also works for other app developers using localhost)
@itwabi I think there are several things which could be improved with your setup here:
OAuth2 should not be used directly from a browser client. If you would like to use OAuth2, you will need to set up a server which keeps a secure Client Secret and communicates with the DHIS2 server directly. The legacy oauth2 endpoints in DHIS2 do not support authorization code flow which would enable PKCE authentication directly from a browser.
CORS is configured differently for oauth2 endpoints than for others, because it should not be used from a browser.
You should never use basic authentication from a web browser, as it risks exposing usernames and passwords. Instead, it is recommended currently to use Cookie sessions.
Implementing a custom React application to communicate with DHIS2 requires a lot of care and configuration. It is recommended instead that you use the DHIS2 Application Platform to build DHIS2 applications (this can be used both for applications deployed directly to the DHIS2 instance, which is recommended, or for applications deployed to external servers). The app platform (and making requests with App Runtime instead of fetch) will automatically handle authentication, authorization, sessions, etc.