使用IdentityServer4身份验证为ClaimsIdentity设置自定义声明 [英] Set custom claims for ClaimsIdentity using IdentityServer4 authentication

查看:644
本文介绍了使用IdentityServer4身份验证为ClaimsIdentity设置自定义声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用IdentityServer4.TokenValidation进行身份验证的ASP.NET Core 2.1应用程序

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;
});

如何向身份添加自定义声明的最佳方法是什么? 考虑到我们仍然需要有机会在Roles验证中使用Authorize属性.

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.

例如,对于承载身份验证,我们可以使用在每个请求上触发的OnTokenValidated处理程序.但是对于IdentityServerAuthenticationOptions,Events属性属于对象类型,并且无法使用具有OnTokenValidated属性的虚拟对象对其进行初始化.

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.

我们必须支持JWT和参考令牌. 我们还需要支持多种身份验证方案

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

有什么想法或建议吗?

推荐答案

范德堡(Ruard van Elburg)给了我一个关于使用中间件的好主意.使用这种方法进行多种身份验证方案时,我唯一需要更新的就是重写IAuthenticationSchemeProvider以便继续使用UseAuthentication中间件.

Ruard van Elburg gave me a good idea about using a middleware. The only thing I had to update use this approach for multiple authentication schemes was overriding IAuthenticationSchemeProvider to keep using UseAuthentication middleware.

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

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

So it returns default scheme based on a request content

我必须要做的:

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
}

这篇关于使用IdentityServer4身份验证为ClaimsIdentity设置自定义声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆