如何在blazor服务器应用中使用signalr从http客户端获取令牌? [英] how to take token from http client with signalr in blazor server app?

查看:541
本文介绍了如何在blazor服务器应用中使用signalr从http客户端获取令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Blazor服务器应用程序中使用SignalR.我在startup.cs文件中添加了services.AddSignalR().那我就不能拿令牌.因为http上下文是null.然后,我从startup.cs文件中删除了services.AddSignalR().这是正常的工作.然后,我可以从http客户端获取令牌.怎么解决呢?

I using SignalR in my Blazor server app. I added services.AddSignalR() in startup.cs file. Then I can't take token. Because http context is null. Then I removed services.AddSignalR() from startup.cs file. it is normal working. Then i can take token from http client. How to solve it?

谢谢.

Startup.cs文件:

Startup.cs file:

services
    .AddAuthentication(options =>
    {
        options.DefaultScheme = "Cookies";
        options.DefaultChallengeScheme = "oidc";
    })
    .AddCookie("Cookies")
    .AddOpenIdConnect("oidc", options =>
    {
        options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.Authority = identityUrl.ToString();
        options.SignedOutRedirectUri = callBackUrl.ToString();
        options.ClientId = useLoadTest ? "mvctest" : "blazor";
        options.ClientSecret = "secret";
        options.ResponseType = useLoadTest ? "code id_token token" : "code id_token";
        options.SaveTokens = true;
        options.GetClaimsFromUserInfoEndpoint = true;
        options.RequireHttpsMetadata = false;
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        options.Scope.Add("post");
        options.Scope.Add("family");
        options.Scope.Add("webpostagg");

    });

services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddSignalR();

services.AddHttpClient<IPostService, PostService>()                  
    .AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>();

HttpClientAuthorizationDelegatingHandler.cs:

public HttpClientAuthorizationDelegatingHandler(IHttpContextAccessor httpContextAccesor)

{
    _httpContextAccesor = httpContextAccesor;
}

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
    string authorizationHeader;
    if (_httpContextAccesor.HttpContext == null)
    {
        authorizationHeader = string.Empty;
    }
    else
    {
        authorizationHeader = _httpContextAccesor.HttpContext
        .Request.Headers["Authorization"];
    }

    if (!string.IsNullOrEmpty(authorizationHeader))
    {
        request.Headers.Add("Authorization", new List<string>() { authorizationHeader });
    }

    var token = await GetToken();

    if (token != null)
    {
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
    }

    return await base.SendAsync(request, cancellationToken);
}

public async Task<string> GetToken()
{
    const string ACCESS_TOKEN = "access_token";

    return await _httpContextAccesor.HttpContext
        .GetTokenAsync(ACCESS_TOKEN);
}

推荐答案

请不要在Server Blazor App中使用HttpContext.不可用.服务器端Blazor是基于WebSocket的,而不是基于HTTP请求的.只是不要这样做.

Please, do not use HttpContext in Server Blazor App. It is not available. Server-side Blazor is WebSocket-based, not HTTP requests based. Just don't do that.

在这里有指向我的答案的链接,这些答案如何实现OpenID Connect,以及在其他地方的问题答案.

Here are links to my answer how to implement OpenID Connect, and others, where you'll find answers to your questions.

请参阅以下内容: 如何在没有Microsoft身份的情况下进行jwt身份验证blazor服务器? 如何从blazor(服务器端)网络应用获取访问令牌? 如何通过IdentityServer4将OpenIdConnect添加到ASP.NET Core ServerSide Blazor Web应用程序? 如何使用服务器端Blazor中的HttpContext对象检索有关用户,用户代理的信息 Blazor添加HttpClientHandler以添加Jwt到请求的HTTP标头

See these: how to jwt authentication blazor server without microsoft identity? How do I get the access token from a blazor (server-side) web app? How to add OpenIdConnect via IdentityServer4 to ASP.NET Core ServerSide Blazor web app? How to get JWT authenticated sign-in user from identity claims in asp.net web api How to use the HttpContext object in server-side Blazor to retrieve information about the user, user agent Blazor Adding HttpClientHandler to add Jwt to HTTP Header on requests

Blazor :没有会话/JWT令牌时重定向到登录页面吗?

注意:还有更多与Jwt,OpenID Connect等相关的答案.您只需寻找它们

Note: There are more answers related to Jwt,OpenID Connect, etc. You just have to look for them

这篇关于如何在blazor服务器应用中使用signalr从http客户端获取令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆