首页 > 解决方案 > Blazor 服务器中的身份验证令牌

问题描述

我有一个使用本地用户帐户保护的 ASP.net 核心 WEB API(使用 WASM blazor 模板创建它)。我可以使用 WASM 客户端成功验证并调用 webapi。

我有一个单独的服务器端 Blazor 应用程序,它尝试调用此 WebAPI,该 WebAPI 再次使用本地用户帐户和相同的身份数据库进行保护)。

在 wasm (webapi) 应用程序中,我配置安全性如下:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));

        services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddCors(options =>
        {
            options.AddPolicy(name: MyAllowSpecificOrigins,
                              builder =>
                              {
                                  builder.WithOrigins("https://localhost:44339");
                              });
        });

        services.AddIdentityServer()
            .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

        services.AddAuthentication()
            .AddIdentityServerJwt();

        services.AddControllersWithViews();
        services.AddRazorPages();

在服务器端应用程序中,我配置安全性如下:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));

        services.AddDefaultIdentity<IdentityUser>(options => { options.SignIn.RequireConfirmedAccount = true;  }) 
                        .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddScoped<AuthenticationStateProvider, 
               RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
        services.AddHttpClient();

在服务器端应用程序中,然后我尝试在 _Host.cshtml 文件中获取令牌,以便我可以将它们添加到客户端标头,但它们总是返回 null。

        AccessToken = await HttpContext.GetTokenAsync("access_token"),
        RefreshToken = await HttpContext.GetTokenAsync("refresh_token")

我在这个安全方面是一个完全的新手,所以很感激我可能完全错了。谁能给我一个关于我是否做错事的指针,或者我是否需要做其他事情来获得这些令牌?

非常感谢戈登

标签: authenticationtokenblazorserver-side

解决方案


推荐阅读