简体   繁体   中英

SignalR authentication with Blazor wasm Bearer Token

I authenticated to Signalr with Bearer token and signalr said Authentication was successful.

认证图片

But Signalr Hub Context.Identity.User.Name is null after authentication.

SignalR 集线器

How can i access to authenticated user information in SignalR Hub for connectionid and user mapping.

My Startup.cs code for authentication.

 services.AddAuthentication(options =>
                    {
                        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                    }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
                    {
                        options.Authority = "https://security.minima.local";
                        options.Audience = "blazor_web_app_api";
                        options.RequireHttpsMetadata = false;
    
                        options.TokenValidationParameters = new
                            TokenValidationParameters()
                            {
                                ValidateAudience = false
                            };
                        options.Events = new JwtBearerEvents
                        {
                            OnMessageReceived = context =>
                            {
                                var accessToken = context.Request.Query["access_token"];
                                var path = context.HttpContext.Request.Path;
                                if (!string.IsNullOrEmpty(accessToken) &&
                                    (path.StartsWithSegments("/notification")))
                                {
                                    context.Token = accessToken;
                                }
    
                                return Task.CompletedTask;
                            }
                        };
                    })
                    .AddIdentityServerJwt();

You need to tell the TokenValidator which claim is the name and role claim and you do that by setting:

.AddMyJwtBearer(opt =>
    {
        ...
        opt.TokenValidationParameters.RoleClaimType = "roles";
        opt.TokenValidationParameters.NameClaimType = "name";

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