asp.net-core - 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?
解决方案
Ruard van Elburg 给了我一个关于使用中间件的好主意。对于多个身份验证方案,我唯一需要更新的就是重写 IAuthenticationSchemeProvider 以继续使用 UseAuthentication 中间件。
因此它根据请求内容返回默认方案
我必须做的:
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
}
推荐阅读
- ruby-on-rails - Active Admin:如何在输入 active_admin rails 时应用搜索过滤器
- swift - 如何将 POST 值发送到 API?[迅速]
- go - GO 获取 K8S api 服务器健康状态
- python - 将 python 函数转换为 pyspark lambda 函数
- arrays - 如何将所有素数放入C中的数组中
- tensorflow - 如何在 tf.keras 中修复这个 AssertionError?
- node.js - 使用 pm2 启动应用程序时如何清除错误?
- python-3.x - AttributeError:“字节”对象在 Python 3.6 中没有属性“编码”
- python - 给定用户名的值错误必须在 django python 项目上设置
- python - 带有单选按钮的选择字段未出现在管理面板上