oidc-client-ts: CORs header missing from sign in callback request

I’ve set up an auth.service.ts file with this package in a react application. After looking at a few similar issues I’ve managed to configure my request config and added the necessary metadata that allows my first redirect to succeed to get to the IDS login page (I was initially having CORs errors but adding the metadata resolved it for the initial sign in request and redirects me to our OIDC login page).

After logging in this then redirects to https://localhost:3000/signin-callback where the secondary part of the PKCE token flow is initiated and the userManager.signinRedirectCallback is fired to then request and retrieve the token to complete authentication. However, this secondary request is being rejected by CORs and failing despite returning a 200 success on the request but still throws a CORS error to the console.

I found that when attempting to utilise the chrome extension CORS unblock the request succeeds and token is fetched with the response headers now containing the values for:

  • Access-Control-Allow-Credentials: true
  • Access-Control-Allow-Methods: *
  • Access-Control-Allow-Origin: https://localhost:3000 Whereas when this extension is disabled these headers are missing and therefore the token request fails to complete.

Essentially I need to add Access-Control-Allow-Origin: https://localhost:3000 to the response headers in the secondary request to the x/connect/token end point for it to be allowed through to complete the token request I believe but I can’t seem to add it via the configuration file. I’ve tried to pass it via extraHeaders on the config but this still seems to fail.

I’d appreciate any help with this as the code is almost functional it is just this issue that seems to be the last obstacle. Below is my current configuration.

export default class AuthService implements IAuthService {
    private userManager: UserManager;

    // Constructor to initialise the UserManager with settings
    constructor() {
        const stsSettings: UserManagerSettings = {
            authority: config.OIDCIssuer,
            client_id: config.ClientId,
            redirect_uri: `${config.OIDCRedirectURI}signin-callback`,
            silent_redirect_uri: config.OIDCRedirectURI,
            scope: config.Scope,
            response_type: "code",
            post_logout_redirect_uri: config.OIDCRedirectURI,
            metadata: {
                issuer: config.OIDCIssuer,
                authorization_endpoint: `${config.OIDCIssuer}/connect/authorize`,
                token_endpoint: `${config.OIDCIssuer}/connect/token`,
                userinfo_endpoint: `${config.OIDCIssuer}/connect/userinfo`,
                end_session_endpoint: `${config.OIDCIssuer}/connect/endsession`
            },
            extraTokenParams: {
                "Access-Control-Allow-Credentials": true,
                "Access-Control-Allow-Methods": "*",
                "Access-Control-Allow-Origin": config.OIDCRedirectURI
            }
        };
        this.userManager = new UserManager(stsSettings);

        // Add event listeners for token expiration and silent renew errors
        this.userManager.events.addAccessTokenExpiring(() => {
            console.log("Token is expiring, attempting silent signin...");
            this.signinSilently();
        });

        this.userManager.events.addSilentRenewError((error) => {
            console.log("Silent renew error:", error.message);
        });
    }

    // Initiate the signin process, redirecting the user to the identity provider
    signin(): Promise<void> {
        console.log("trying to redirect");
        return this.userManager.signinRedirect({ state: window.location.href });
    }

    // Complete the signin process, handling the callback after redirection
    completeSignin(): Promise<User> {
        const returnUrl =
            window.location.href !== "/" ? window.location.href : "";
        return this.userManager
            .signinRedirectCallback(returnUrl)
            .then((user) => {
                return user;
            });
    }

// Attempt to signin silently, renewing the access token without user interaction
    signinSilently(): Promise<User | void> {
        console.log("Attempting silent signin...");
        return this.userManager.signinSilent().then(
            (user) => {
                console.log("Silent signin successful");
                return user;
            },
            (error) => {
                console.log("Silent signin failed:", error);
                // If silent signin fails, initiate a regular signin
                this.signin();
            }
        );
    }

    // Handle the silent signin callback
    silentSignInCallback(): Promise<void> {
        return this.userManager.signinSilentCallback() as Promise<void>;
    }

    // Initiate the signout process, redirecting the user to the identity provider
    signout(): Promise<void> {
        return this.userManager.signoutRedirect();
    }

    // Get the access token if available and not expired
    getAccessToken(): Promise<string | null> {
        return this.userManager.getUser().then((user) => {
            if (!!user && !user.expired) {
                return user.access_token;
            } else {
                return null;
            }
        });
    }
}

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Comments: 17 (7 by maintainers)

Most upvoted comments

I think the request here was poorly formulated.

We should have talked about “the need to add extra headers to requests” in a generic way and not about the “why” it’s needed. If some folks then wants to add Access-Control-Allow-Origin as an extra header, which is completely ridiculous, then it’s their responsibility.

@JMZiem, you first talked about sending Access-Control-Allow-Origin whereas you should have talked about sending Origin. Sending Access-Control-Allow-Origin yourself is the same as not having CORS enabled at all. It should be the responsibility of the browser to send the Origin header and the responsibility of the server to checks that header and, if configured to allow that origin, responds with the appropriate Access-Control-Allow-Origin. CORS is a browser security feature and as such a web app cannot decide itself whether it should be allowed or not. This is a nonsense.

All this has created confusion and taken us away from the main problem. People tried to help you by making you understand that maybe you were misunderstanding things and that the problem was elsewhere. Where in fact, the issue, in your case, was that the browser is not sending the Origin header properly. But this is another topic.

So before complaining about the library or about a “refusal to add anything” (which we don’t actually, because this is still an ongoing discussion), try to be more constructive next time by doing what you did last, ie. highlights, where and why, what you requested if not functioning or miss-functioning, or even better submit a PR.

Thank you