您好,欢迎来到筏尚旅游网。
搜索
您的当前位置:首页关于SignalR的身份认证问题

关于SignalR的身份认证问题

来源:筏尚旅游网

前置笔记:

var services = builder.Services;
services.Configure<JWTOptions>(builder.Configuration.GetSection("JWT"));
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(x =>
{
	var jwtOpt = builder.Configuration.GetSection("JWT").Get<JWTOptions>();
	byte[] keyBytes = Encoding.UTF8.GetBytes(jwtOpt.SigningKey);
	var secKey = new SymmetricSecurityKey(keyBytes);
	x.TokenValidationParameters = new() {ValidateIssuer = false,
		ValidateAudience = false, ValidateLifetime = true,
		ValidateIssuerSigningKey = true, ssuerSigningKey = secKey};

    // 新增的部分
    x.Events = new JwtBearerEvents
    {
        OnMessageReceived = context =>
        {
            var accessToken = context.Request.Query["access_token"];
            var path = context.HttpContext.Request.Path;
            if (!string.IsNullOrEmpty(accessToken) &&
                (path.StartsWithSegments("/Hubs/ChatRoomHub"))) context.Token = accessToken;
           return Task.CompletedTask;
        }
    };
});

5、app.UseAuthorization()这行代码之前添加app.UseAuthentication()。

6、在控制器类Test1Controller中增加登录并且创建JWT令牌的操作方法Login。返回JWT。

7、在需要登录才能访问的集线器类上或者方法上添加[Authorize]。也支持角色等设置,可以设置到Hub或者方法上。

const startConn = async function () {
	const transport = signalR.HttpTransportType.WebSockets;
	const options = { skipNegotiation: true, transport: transport };
    // 这一行 很重要  看一下 啊啊啊啊啊!!!!!
	options.accessTokenFactory = () => state.accessToken;
	connection = new signalR.HubConnectionBuilder()
		.withUrl('https://localhost:7047/Hubs/ChatRoomHub', options)
		.withAutomaticReconnect().build();
	await connection.start();
	connection.on('ReceivePublicMessage', msg => {
 		state.messages.push(msg);
 	});
 	alert("登陆成功可以聊天了");
 };

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- efsc.cn 版权所有 赣ICP备2024042792号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务