2 回答
TA贡献1852条经验 获得超1个赞
如果您使用自己的自定义令牌,您可以这样做:
客户端(.NET,但我想你会理解的):
var connection = new HubConnection("url", "CustomToken=SomeToken");
connection.Start().Wait();
服务器:
public override Task OnConnected()
{
if(Context.QueryString["CustomToken"] != "CorrectToken")
{
///Forcefully close the connection
HttpContext.Current.Response.Close();
}
return base.OnConnected();
}
TA贡献1824条经验 获得超8个赞
在这种情况下,您可以使用 JWT 令牌。配置非常简单:
您Program.cs应该配置 JWT:
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = configuration["Jwt:Issuer"],
ValidAudience = configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"])),
ClockSkew = TimeSpan.Zero
};
cfg.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
if (context.Request.Query.TryGetValue("token", out var token)
)
context.Token = token;
return Task.CompletedTask;
}
};
});
配置文件:
"Jwt": {
"Key": "someKey",
"Issuer": "http://yourdomain.com",
"ExpireDays": 0,
"ExpireHours": 1,
"ExpireMinutes": 0
},
在 Angular 中,您应该创建拦截器,它将向每个请求添加 Authentications 标头:
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private userContext: UserContext) { }
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const authToken = this.userContext.getToken();
if (!!authToken) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${authToken}`
}
});
}
return next.handle(request);
}
}
- 2 回答
- 0 关注
- 139 浏览
添加回答
举报