首页 > 解决方案 > Set custom claims for ClaimsIdentity using IdentityServer4 authentication

问题描述

I have an ASP.NET Core 2.1 application authenticated using IdentityServer4.TokenValidation

authenticationBuilder.AddIdentityServerAuthentication(AuthorizationConstants.IpreoAccountAuthenticationScheme, options =>
    {
      options.RequireHttpsMetadata = false;
      options.ApiName = apiName;
      options.ApiSecret = apiSecret;
      options.Authority = authority;
      options.LegacyAudienceValidation = true;
    });

What is the best way how can I add custom claims to identity? Taking into account that we still need to have an opportunity to use Authorize attribute with Roles validation.

For bearer authentication for example we can use OnTokenValidated handler which is fired on each request. But for IdentityServerAuthenticationOptions Events property is of type of object and initializing it with a dummy object with OnTokenValidated property does not work.

We have to support JWT and reference tokens. Also we need to support multiple authentication schemes

Any ideas or suggestions?

标签: asp.net-coreidentityserver4

解决方案


Ruard van Elburg 给了我一个关于使用中间件的好主意。对于多个身份验证方案,我唯一需要更新的就是重写 IAuthenticationSchemeProvider 以继续使用 UseAuthentication 中间件。

https://github.com/aspnet/Security/blob/beaa2b443d46ef8adaf5c2a89eb475e1893037c2/src/Microsoft.AspNetCore.Authentication/AuthenticationMiddleware.cs

因此它根据请求内容返回默认方案

我必须做的:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseAuthentication();
    app.UseMiddleware<ClaimsMiddleware>(); // to set claims for authenticated user
    app.UseMvc();
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);    
    services.AddTransient<IAuthenticationSchemeProvider, CustomAuthenticationSchemeProvider>(); 
    services.AddAuthorization();
    services.AddAuthentication // add authentication for multiple schemes
}

推荐阅读