简体   繁体   中英

How to validate Azure AD B2C token from query string in Asp.net Core?

I have a asp.net web api application with some controllers and a signalR hub. JWT tokens validation with Azure AD B2C is configured like this:

services.AddAuthentication(AzureADB2CDefaults.JwtBearerAuthenticationScheme)
        .AddAzureADB2CBearer(options => _configuration.Bind("AzureAdB2C", options))

This works fine with controllers, and I don't have to worry about the intricacies of Azure AD B2C token validation .

Now, for the signalR hub to support Web Sockets or Server-sent events, the authentication token should be read from the querystring . I'm supposed to handle the OnMessageReceived event like this :

services.AddAuthentication(...)
    .AddJwtBearer(options =>
        {
            options.Events = new JwtBearerEvents
            {
                OnMessageReceived = context =>
                {
                    var accessToken = context.Request.Query["access_token"];

                    // If the request is for our hub...
                    var path = context.HttpContext.Request.Path;
                    if (!string.IsNullOrEmpty(accessToken) &&
                        (path.StartsWithSegments("/hubs/chat")))
                    {
                        // Read the token out of the query string
                        context.Token = accessToken;
                    }
                    return Task.CompletedTask;
                }
            };
        });

Unfortunately, the AzureAdB2COptions object does not give me access to the authentication events.

How can I reconcile both approaches ?

Maybe get a little more manual by writing your own AuthenticationHandler. You can use the IServiceCollection extensions of .AddAuthorization and .AddAuthentication to write your own logic that does the things that are supposed to happen.

What I find with C# in a post-dotnet core world, use as little of their framework as is necessary to hook in to it. The framework stuff is all janky and brittle, and in 5 years when they've redone it all 3 times nobody will be able to maintain the bizarre 5-year old fluent builder stuff in every Startup.cs.

Writing your own AuthenticationHandler is a good compromise between using a single-line fluent builder extension method vs. completely ignoring the entire framework and writing your own framework that uses logic and reason.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM