Search code examples
javascriptreactjsoauth-2.0oauthopenid-connect

Allow CORS in react-oidc-context/oidc-react


I want to add OAuth to my react application using a custom OAuth authentication provider. I have tried to use react-oidc-context and oidc-react, but with both libraries, I get blocked by CORS policy. I cannot figure out how I add the Access-Control-Allow-Origin header since the libraries request the openid-configuration-file from the auth provider under the hood. I can pass metadata or UserManager to the AuthProvider, which, as the docs say, "Provide metadata when authority server does not allow CORS on the metadata endpoint", but I cannot figure out how to use them/what value to pass since there is no example.

Is there a way that I can add the CORS-header or another way of making the OIDC-call?


Solution

  • CORS is something that needs to be configured in the Authorization Server (AS) when your React client is registered. Almost all ASs support CORS these days. You cannot make it work from React code.

    LIBRARY SETTINGS

    My code example shows an SPA config, and an alternative to downloading metadata is to provide a metadata JSON object with endpoint locations:

    authorize_endpoint
    end_session_endpoint
    token_endpoint
    jwks_endpoint
    

    However, when the library calls the last two endpoints it will still need to make cross origin requests.

    BACK END PROXYING

    If the AS definitely does not support CORS then one option is to double hop calls to the last two endpoints via your own back end component. This should not be necessary with any up to date AS though.