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

我是研究僧i 提交于 2019-12-24 07:26:18

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/56239040/how-to-validate-azure-ad-b2c-token-from-query-string-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!