Access has been blocked by CORS policy when redirecting to login.microsoft

Teodorescu, A.C. (Andrei - Calin) 0 Reputation points
2024-09-19T10:56:52.6933333+00:00

Hello,

I have a web app (javascript front-end with a .NET Core 6 Web API) and I am trying to add authentication via OpenId connect and my redirects to login.microsoft are blocked by a CORS, if I hit the refresh button on the browser the redirect to login.microsoft works and the authentication is fine, but if the redirect happens without refresh it does not work. What I am doing wrong or what is missing? Below you can find my Web API auth configuration.

    public static WebApplicationBuilder AddAuthenticationViaOpenIdConnect(this WebApplicationBuilder builder)
    {
        var serviceCollection = builder.Services;
        var configuration = builder.Configuration;

        serviceCollection.AddAuthentication(options =>
            {
                // our authentication process will used signed cookies
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                // our authentication challenge is openid
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.Cookie.Name = "oidc";
                options.Cookie.SameSite = SameSiteMode.None;
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                options.Cookie.IsEssential = true;
            })
            .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
            {
                options.NonceCookie.SecurePolicy = CookieSecurePolicy.Always;
                options.CorrelationCookie.SecurePolicy = CookieSecurePolicy.Always;
                // How middleware persists the user identity? (Cookie)
                options.SignInScheme =
                    CookieAuthenticationDefaults.AuthenticationScheme;
                options.GetClaimsFromUserInfoEndpoint = true;
                // How Browser redirects user to authentication provider?
                // (direct get)
                options.AuthenticationMethod =
                    OpenIdConnectRedirectBehavior.RedirectGet;

                // How response should be sent back from authentication provider?
                //(form_post)
                options.ResponseMode = OpenIdConnectResponseMode.FormPost;

                // Who is the authentication provider? (IDP)
                options.Authority = configuration["Azure:Authority"];

                // Who are we? (client id)
                options.ClientId = configuration["Azure:ClientId"];

                // How does authentication provider know, we are legit? (secret key)
                options.ClientSecret = configuration["Azure:Secret"];

                // What do we intend to receive back?
                // (code to make for consequent requests)
                options.ResponseType = OpenIdConnectResponseType.Code;

                // Should there be extra layer of security?
                // (false: as we are using hybrid)
                options.UsePkce = false;

                // Where we would like to get the response after authentication?
                options.CallbackPath = configuration["Azure:CallbackPath"];

                // Should we persist tokens?
                options.SaveTokens = true;

                // Should we request user profile details for user end point?
                options.GetClaimsFromUserInfoEndpoint = true;
                options.SkipUnrecognizedRequests = true;

                // What scopes do we need?
                //options.Scope.Add("sid");
                //options.Scope.Add("email");
                //options.Scope.Add("acct");
                //options.Scope.Add("upn");
                //options.Scope.Add("groups");


                // How to handle OIDC events?
                options.Events = new OpenIdConnectEvents
                {
                    OnRedirectToIdentityProviderForSignOut = context =>
                    {
                        context.Response.Redirect(configuration["Azure:RedirectOnSignOut"]);
                        context.HandleResponse();

                        return Task.CompletedTask;
                    },

                    // Where to redirect when we get authentication errors?
                    OnRemoteFailure = context =>
                    {
                        context.Response.Redirect("/error");
                        context.HandleResponse();
                        return Task.FromResult(0);
                    }
                };
            });

        return builder;
    }

Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
21,762 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Raja Pothuraju 6,440 Reputation points Microsoft Vendor
    2024-10-07T23:39:18.05+00:00

    Hello @Teodorescu, A.C. (Andrei - Calin), I'm glad that you were able to resolve your issue and thank you for posting your solution so that others experiencing the same thing can easily reference this! Since the Microsoft Q&A community has a policy that "The question author cannot accept their own answer. They can only accept answers by others ", I'll repost your solution in case you'd like to "Accept " the answer.

    Issue: Access has been blocked by CORS policy when redirecting to login.microsoft

    Solution: Resolved by @Teodorescu, A.C. (Andrei - Calin)

    "After registering the Single Page Application (SPA), linking it to the Web API, and implementing Microsoft Authentication Library (MSAL) on the front-end resolved the issue.

    More details here:

    https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow

    https://learn.microsoft.com/en-us/answers/questions/353629/cors-issue-while-getting-token-with-oauth-2-0-clie

    https://www.youtube.com/watch?v=rgPZVmsMf5c&t=1203s (here it is video that explains step by step how to register a SPA)"

    If you have any other questions or are still running into more issues, please let me know. Thank you again for your time and patience throughout this issue.

    Please remember to "Accept Answer" if any answer/reply helped, so that others in the community facing similar issues can easily find the solution.

    Thanks,
    Raja Pothuraju.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.