CORS issue in a hosted Blazor solution

anastasia 21 Reputation points
2022-04-26T12:29:02.263+00:00

I have a hosted Blazor app based on Blazor webAssembly project template. I use azure AD B2C standard user flow for user authentication. I can log in when I run the app on the localhost, but I can not access endpoints from a controller that requires user to be authenticated. The issue seems to be CORS related and happens while sending request to https://xxx.b2clogin.com/xxx.onmicrosoft.com/b2c_1_signin/oauth2/v2.0/authorize:
196500-image.png

I use a custom AuthorizationMessageHandler class, as reccomended here and register it in the client's services like that:

builder.Services.AddScoped<CustomAuthorizationMessageHandler>();  
builder.Services.AddHttpClient("xxxAPI",  
        client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))  
    .AddHttpMessageHandler<CustomAuthorizationMessageHandler>();  

CustomAuthorizationMessageHandler:

public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler  
    {  
        public CustomAuthorizationMessageHandler(IAccessTokenProvider provider,  
            NavigationManager navigationManager)  
            : base(provider, navigationManager)  
        {  
            ConfigureHandler(  
                authorizedUrls: new[] {"https://xxx.b2clogin.com/"},  
                scopes: new[] {"user.read", "user.write"});  
        }  
    }  

Am I missing something else?

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,385 questions
Microsoft Entra External ID
Microsoft Entra External ID
A modern identity solution for securing access to customer, citizen and partner-facing apps and services. It is the converged platform of Azure AD External Identities B2B and B2C. Replaces Azure Active Directory External Identities.
2,639 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,601 Reputation points
    2022-04-26T15:41:46.76+00:00

    the api you are calling appears to be redirecting to the azure ad oauth login server (probably using web flow). the ad login server does not support Ajax logins.

    typically the blazer app would use msal client library to login in, then use the returned token to call the webapi. the webapi should just return a 401 for missing/invalid jwt token, not a redirect.

    https://learn.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/standalone-with-azure-active-directory?view=aspnetcore-6.0

    note: if you want to use web flow and cookies, then the index.html page should require authentication. you should change the webapi to return 401 error rather than redirect. on the client side if you get a 401 error (expired token), set location to index.html, which force a reload and authentication.