How to combine multiple authentication schemes for different types of clients (user/pass and client/secret) in a Blazor WASM project?

此生再无相见时 提交于 2021-01-05 08:53:38

问题


I have a Blazor WASM project with a Blazor Client and ASP.NET core server. I can authenticate with user/password using the following code:

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

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

services
    .AddAuthentication()
    .AddIdentityServerJwt();

services.AddTransient<IProfileService, ProfileService>();

services.AddAuthorization(options =>
{
    options.AddPolicy("ApiScope", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireClaim("scope", "api1");
    });
});

When I add the following code, I can successfully authenticate with clientcredentials from a console client. But then the Blazor client user/password authentication stops working.

...

services
    .AddIdentityServer()
    .AddApiAuthorization<ApplicationUser, ApplicationDbContext>()
    +.AddInMemoryApiScopes(Config.ApiScopes)
    +.AddClientStore<ClientStore>()
    +.AddDeveloperSigningCredential();

services
    .AddAuthentication()
    .AddIdentityServerJwt();

+services
+    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
+    .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
+    {
+        options.Authority = "https://localhost:44311";
+        options.TokenValidationParameters = new TokenValidationParameters
+        {
+            ValidateAudience = false,
+        };
+    });

...

In the browser while trying to authenticate in the Blazor client, the console prints:

info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed. These requirements were not met:
      DenyAnonymousAuthorizationRequirement: Requires an authenticated user.

I have tried a lot, but I'm not able to make both work together. It seems that somehow this configuration requires authentication for everything, even the pages/controllers that are marked AllowAnonymous. So, when I try to authenticate, it gives me an error telling me the user must be authenticated: DenyAnonymousAuthorizationRequirement. The policy, "ApiScope" is only intended for the clientcredentials client, not for the Blazor client. If removed, the RequireAuthenticatedUser call doesn't make a difference, same error.

Any help is appreciated.

来源:https://stackoverflow.com/questions/64955291/how-to-combine-multiple-authentication-schemes-for-different-types-of-clients-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!