AngularSignalR认证问题
创始人
2024-10-29 15:31:40
0
  1. 在服务器端实现SignalR的Token认证逻辑。

  2. 通过使用SignalR的JwtBearer认证提供程序,配置服务器端SignalR发送授权令牌。

  3. 在客户端上使用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();
     }
    

    } }

  4. 在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, next: Http

相关内容

热门资讯

德扑之心免费透视!pokemm... 德扑之心免费透视!pokemmo手机辅助软件(透视)技巧-都是解密真的是有挂1、完成pokemmo手...
佛手在线大菠萝为什么都输!we... 您好,佛手在线大菠萝为什么都输这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302...
wepoker有辅助工具吗!h... wepoker有辅助工具吗!hhpoker德州挂真的有吗(透视)脚本-切实揭幕是真的挂1、让任何用户...
wepoker有没有机器人!h... wepoker有没有机器人!hh poker软件(透视)教程-好像普及真的是有挂1、完成wepoke...
wepoker轻量版有透视吗!... wepoker轻量版有透视吗!aapoker怎么拿好牌(透视)插件-切实普及是有挂1、进入到wepo...
pokemmo手机辅助软件!w... pokemmo手机辅助软件!wpk软件是正规的吗(透视)工具-都是总结真的是有挂1)pokemmo手...
wepoker俱乐部辅助!po... wepoker俱乐部辅助!pokeplus脚本(透视)技巧-其实科普是有挂1、wepoker俱乐部辅...
wepoker破解器有用吗!w... wepoker破解器有用吗!wepoker私人局规律(透视)教程-都是揭露是有挂1、这是跨平台的we...
wejoker辅助机器人!德州... wejoker辅助机器人!德州真人透视脚本(透视)神器-都是曝光存在有挂德州真人透视脚本破解侠是真的...
wpk有透视吗!来玩app破解... wpk有透视吗!来玩app破解(透视)挂-其实解迷存在有挂1、来玩app破解模拟器是什么优化,来玩a...