亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

ASP.NET Core SignalR 使用 Azure AD 返回 401 未經授權

ASP.NET Core SignalR 使用 Azure AD 返回 401 未經授權

C#
慕斯709654 2023-09-24 17:19:29
我有一個 SPA (Angular 7) 和一個 API (.Net Core),我使用 Azure AD 對其進行身份驗證。我正在使用adal-angular4將我的角度應用程序與 AAD 集成。一切都很好,但我也使用 SignalR 和 API 作為服務器,當我嘗試從 SPA 連接時,我在協商“請求”上收到 401 Unauthorized 消息,并在響應標頭中得到此消息:該請求在 Authorization 標頭中包含我的 Bearer 令牌,當我通過jwt.io運行該令牌時,我可以看到“aud”值是我的 SPA 的 Azure AD ClientId。對 API 的所有常規請求都包含相同的令牌,我對此沒有任何問題。我的所有控制器和集線器上都有[授權],但只有 SignalR 集線器會導致此問題。我的 SignalR 中心:[Authorize]public class MainHub : Hub{    private readonly IEntityDbContext _ctx;    public MainHub(IEntityDbContext ctx)    {        _ctx = ctx;        _signalRService = signalRService;    }    public override Task OnConnectedAsync()    {        return base.OnConnectedAsync();    }    public override Task OnDisconnectedAsync(Exception exception)    {        return base.OnDisconnectedAsync(exception);    }}這是我的 Angular 客戶端上的 SignalRService。我在 app.component.ts 的構造函數中運行 startConnection() 。export class SignalRService {    private hubConnection: signalR.HubConnection;    constructor(private adal: AdalService) {}    startConnection(): void {        this.hubConnection = new signalR.HubConnectionBuilder()            .withUrl(AppConstants.SignalRUrl, { accessTokenFactory: () => this.adal.userInfo.token})            .build();        this.hubConnection.serverTimeoutInMilliseconds = 60000;        this.hubConnection.on('userConnected', (user) =>         {            console.log(user);        });        this.hubConnection.start()            .then(() => console.log('Connection started'))            .catch(err =>             {                console.log('Error while starting connection: ' + err);            });    }}我已經嘗試過這個解決方案,但我也無法讓它發揮作用。
查看完整描述

1 回答

?
泛舟湖上清波郎朗

TA貢獻1818條經驗 獲得超3個贊

您需要對 JWT Bearer 事件進行特殊處理,以便您的身份驗證正常工作。令牌需要轉發到集線器??纯次艺f的部分

那部分不見了

public void ConfigureServices(IServiceCollection services)

{

? ? services.AddDbContext<ApplicationDbContext>(options =>

? ? ? ? options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


? ? services.AddIdentity<ApplicationUser, IdentityRole>()

? ? ? ? .AddEntityFrameworkStores<ApplicationDbContext>()

? ? ? ? .AddDefaultTokenProviders();


? ? services.AddAuthentication(options =>

? ? ? ? {

? ? ? ? ? ? // Identity made Cookie authentication the default.

? ? ? ? ? ? // However, we want JWT Bearer Auth to be the default.

? ? ? ? ? ? options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;

? ? ? ? ? ? options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

? ? ? ? })

? ? ? ? .AddJwtBearer(options =>

? ? ? ? {

? ? ? ? ? ? // Configure JWT Bearer Auth to expect our security key

? ? ? ? ? ? options.TokenValidationParameters =

? ? ? ? ? ? ? ? new TokenValidationParameters

? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? LifetimeValidator = (before, expires, token, param) =>

? ? ? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? ? ? return expires > DateTime.UtcNow;

? ? ? ? ? ? ? ? ? ? },

? ? ? ? ? ? ? ? ? ? ValidateAudience = false,

? ? ? ? ? ? ? ? ? ? ValidateIssuer = false,

? ? ? ? ? ? ? ? ? ? ValidateActor = false,

? ? ? ? ? ? ? ? ? ? ValidateLifetime = true,

? ? ? ? ? ? ? ? ? ? IssuerSigningKey = SecurityKey

? ? ? ? ? ? ? ? };


? ? ? ? ? ? //THAT IS THE PART WHICH IS MISSING IN YOUR CONFIG !

? ? ? ? ? ? // We have to hook the OnMessageReceived event in order to

? ? ? ? ? ? // allow the JWT authentication handler to read the access

? ? ? ? ? ? // token from the query string when a WebSocket or?

? ? ? ? ? ? // Server-Sent Events request comes in.

? ? ? ? ? ? options.Events = new JwtBearerEvents

? ? ? ? ? ? {

? ? ? ? ? ? ? ? OnMessageReceived = context =>

? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? var accessToken = context.Request.Query["access_token"];


? ? ? ? ? ? ? ? ? ? // If the request is for our hub...

? ? ? ? ? ? ? ? ? ? var path = context.HttpContext.Request.Path;

? ? ? ? ? ? ? ? ? ? if (!string.IsNullOrEmpty(accessToken) &&

? ? ? ? ? ? ? ? ? ? ? ? (path.StartsWithSegments("/hubs/chat")))

? ? ? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? ? ? // Read the token out of the query string

? ? ? ? ? ? ? ? ? ? ? ? context.Token = accessToken;

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? return Task.CompletedTask;

? ? ? ? ? ? ? ? }

? ? ? ? ? ? };

? ? ? ? });


? ? services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);


? ? services.AddSignalR();


? ? // Change to use Name as the user identifier for SignalR

? ? // WARNING: This requires that the source of your JWT token?

? ? // ensures that the Name claim is unique!

? ? // If the Name claim isn't unique, users could receive messages?

? ? // intended for a different user!

? ? services.AddSingleton<IUserIdProvider, NameUserIdProvider>();


? ? // Change to use email as the user identifier for SignalR

? ? // services.AddSingleton<IUserIdProvider, EmailBasedUserIdProvider>();


? ? // WARNING: use *either* the NameUserIdProvider *or* the?

? ? // EmailBasedUserIdProvider, but do not use both.?

}


查看完整回答
反對 回復 2023-09-24
  • 1 回答
  • 0 關注
  • 200 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號