在服务器端实现SignalR的Token认证逻辑。
通过使用SignalR的JwtBearer认证提供程序,配置服务器端SignalR发送授权令牌。
在客户端上使用JwtInterceptor拦截器,将Jwt令牌添加到每个SignalR请求的标头中。 示例: [Authorize] public class ChatHub : Hub { // 必须与前端代码一致 private const string HUB_PATH = "/mychat";
public async Task SendMessage(string message) { await Clients.All.SendAsync("ReceiveMessage", message); } public override async Task OnConnectedAsync() { // 通过获取JWT令牌,验证并处理请求 var httpContext = Context.GetHttpContext(); var header = httpContext.Request.Headers["Authorization"].ToString();
// 获取JWT令牌
var token = header.Split(" ")[1];
// 验证JWT令牌
var validatedToken = new JwtSecurityToken(token);
// 处理请求,没有问题才能继续
if (validatedToken.ValidTo > DateTime.Now)
{
await base.OnConnectedAsync();
}
else
{
// 鉴定没过就断开连接
Context.Abort();
}
} }
在Angular app.module.ts文件中,添加JwtInterceptor拦截器:
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { JwtInterceptor } from './jwt.interceptor';
@NgModule({
...
providers: [
...
{
provide: HTTP_INTERCEPTORS,
useClass: JwtInterceptor,
multi: true
}
]
})
export class AppModule { }
示例:
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { AuthService } from './auth.service';
import { Observable } from 'rxjs';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) { }
intercept(request: HttpRequest