【问题标题】:Token is coming as null from GetTokenAsync in Blazor Server令牌来自 Blazor 服务器中的 GetTokenAsync 为 null
【发布时间】:2022-08-04 16:31:30
【问题描述】:

我创建了一个 blazor 服务器应用程序(.NET6),并使用 JWT 身份验证通过引用此 Microsoft document 对应用程序进行身份验证。当要获取保存在本地存储中的令牌时,我得到一个空值。

我的程序.cs

            var builder = WebApplication.CreateBuilder(args);
                       ...
    
            builder.Services.AddRazorPages();
            builder.Services.AddServerSideBlazor();
            builder.Services.AddHttpContextAccessor();
            builder.Services.AddScoped<TokenProvider>();
            builder.Services.AddHttpClient();
        
        
            builder.Services.AddAuthentication(options =>
                         {
                             options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                             options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                             options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                         })
                        .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, x =>
                         {
                             x.RequireHttpsMetadata = false;
                             x.SaveToken = true;
                         });


   if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler(\"/Error\");
        app.UseHsts();
    }
    ...
    app.UseHttpsRedirection();
    
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.MapBlazorHub();
    app.MapFallbackToPage(\"/_Host\");
    
    app.Run();

TokenProvider.cs

public class TokenProvider
{
    public string AccessToken { get; set; }
    public string RefreshToken { get; set; }
}

初始应用程序状态.cs

public class InitialApplicationState
{
    public string AccessToken { get; set; }
    public string RefreshToken { get; set; }
}

Pages/_Host.cshtml 文件,

@using Microsoft.AspNetCore.Authentication

...

@{
    var tokens = new InitialApplicationState
    {
        AccessToken = await HttpContext.GetTokenAsync(\"access_token\"),
        RefreshToken = await HttpContext.GetTokenAsync(\"refresh_token\")
    };
}

<component type=\"typeof(App)\" param-InitialState=\"tokens\" 
    render-mode=\"ServerPrerendered\" />

我在上面的代码中将此 AccessToken 和 RefreshToken 作为 null

App.razor

    @inject TokenProvider TokenProvider

...

@code {
    [Parameter]
    public InitialApplicationState InitialState { get; set; }

    protected override Task OnInitializedAsync()
    {
        TokenProvider.AccessToken = InitialState.AccessToken;
        TokenProvider.RefreshToken = InitialState.RefreshToken;

        return base.OnInitializedAsync();
    }
}

在这里我设置 tokenprovider 令牌值,但它被设置为空值,因为 InitialState 令牌为空 所以我需要知道为什么会发生这种情况??,我错在哪里?请帮我

    标签: .net-core jwt blazor-server-side bearer-token


    【解决方案1】:

    我使用 Microsoft.AspNetCore.Authentication.OpenIdConnect 包。

    builder.Services.AddAuthentication(opt =>
    {
        opt.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        opt.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    }).AddCookie().AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
    {
        options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.Authority = GlobalConstants.IDENTITY_SERVER_URL;
        options.ClientId = GlobalConstants.IDENTITY_SERVER_CLIENT;
        options.SaveTokens = true;
        /// Set here ClientSecret ResponseType and add scopes
    }
    

    它对我有用,成功检索访问令牌。

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 2020-08-20
      • 1970-01-01
      • 2022-11-09
      • 2017-06-10
      • 2020-05-09
      • 1970-01-01
      • 2017-06-05
      • 1970-01-01
      相关资源
      最近更新 更多