簡體   English   中英

在 Blazor wasm 中自動將身份 Cookie 附加到 HTTP 客戶端

[英]Automatically Attaching Identity Cookie to HTTP Client in Blazor wasm

我正在開發一個 blazor 應用程序,其中我使用我的 API 項目作為身份

提供者。 一切正常,但問題是訪問令牌

我的 API 發布的 API 未經過驗證。 事實證明,API 期待一個

餅干頭。 我仔細查看了 blazor 托管應用程序並發現

cookie 與每個請求一起發送,但它是同源的。

我的 Blazor WASM 項目不會在請求中自動附加此 cookie

標頭,只是訪問令牌。

有沒有辦法讓 Http 處理程序在每個請求上附加這個 cookie?

或者讓 API 驗證訪問令牌而不是身份 cookie。

這是我在 API 項目中的啟動類

       public static void AddIdentityServer(IServiceCollection services,IConfiguration configuration)
        {
            services.AddIdentityServer(options =>
            {
                options.UserInteraction.LoginUrl = "/Identity/Account/Login";
                options.UserInteraction.LogoutUrl = "/Identity/Account/Logout";
            }).AddProfileService<LocalProfileService>()
             .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(option =>
             {
                 option.Clients.Add(new Client
                 {
                     ClientId = "blazor",
                     AllowedGrantTypes = GrantTypes.Code,
                     RequirePkce = true,
                     RequireClientSecret = false,
                     AllowedCorsOrigins = { "https://localhost:5001" },
                     AllowedScopes = { "openid", "profile", "email","id" },
                     RedirectUris = { "https://localhost:5001/authentication/login-callback" },
                     PostLogoutRedirectUris = { "https://localhost:5001/" },
                     Enabled = true,
                     RequireConsent = false,  
                 });
                 option.IdentityResources.AddEmail();
                 option.IdentityResources["openid"].UserClaims.Add("name");
                 option.ApiResources.Single().UserClaims.Add("name");
                 option.IdentityResources["openid"].UserClaims.Add("role");
                 option.ApiResources.Single().UserClaims.Add("role");

                 option.IdentityResources.Add(new IdentityResource("id",new string[] {"id" }));
                 option.ApiResources.Single().UserClaims.Add("id");
                 

             });

            services.AddAuthentication()
                .AddGoogle("Google", options =>
                {
                    options.ClientId = configuration["ExternalLoginApiKey:GoogleClientId"];
                    options.ClientSecret = configuration["ExternalLoginApiKey:GoogleClientSecret"];
                })
                .AddFacebook("Facebook", options =>
                {
                    options.AppId = configuration["ExternalLoginApiKey:FacebookAppId"];
                    options.AppSecret = configuration["ExternalLoginApiKey:FacebookAppSecret"];
                })
               .AddIdentityServerJwt();

          
        }

Blazor 項目中的程序類

        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("app");

            builder.Services.AddOidcAuthentication(options =>
            {
                builder.Configuration.Bind("oidc", options.ProviderOptions);
                options.UserOptions.RoleClaim = "role";
            }).AddAccountClaimsPrincipalFactory<CustomUserFactory>();

            builder.Services.AddHttpClient<IAuthorizedRestService, AuthorizedRestService>(
               client => client.BaseAddress = new Uri("https://localhost:5002/api/mart/v1/"))
                 .AddHttpMessageHandler(sp => sp.GetRequiredService<AuthorizationMessageHandler>()
            .ConfigureHandler(authorizedUrls: new[] { "https://localhost:5002" }));


            builder.Services.AddHttpClient("noauth", option => option.BaseAddress = new 
              Uri("https://localhost:5002/api/mart/v1/"));

            builder.Services.AddScoped<IRestService, RestService>();

            await builder.Build().RunAsync();
        }

我找到了解決方案。

碰巧 IdentityServer4 已經為 API 提供了一個 JWT 處理程序,可以兼作授權服務器

 .AddIdentityServerJwt();

所以我所做的是配置它

      services.Configure<JwtBearerOptions> 
       (IdentityServerJwtConstants.IdentityServerJwtBearerScheme,
                options =>
                {
                    options.Authority = "https://localhost:5002";
                    options.Audience = "mart";
                    options.SaveToken = true;
                });

然后指定要使用的身份驗證方案

    [Authorize(AuthenticationSchemes = IdentityServerJwtConstants.IdentityServerJwtBearerScheme)]

也可以在啟動類中全局添加

 var authorizationPolicy = new AuthorizationPolicyBuilder(IdentityServerJwtConstants.IdentityServerJwtBearerScheme)
                .RequireAuthenticatedUser().Build();
                options.Filters.Add(new AuthorizeFilter(authorizationPolicy));

您可以使用這些鏈接閱讀更多信息

https://docs.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme?view=aspnetcore-3.1

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-api-authorization?view=aspnetcore-3.1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM