[英]Is there a way to add claims in an ASP.NET Core middleware after Authentication?
I have this in my startup:我在我的启动中有这个:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSwaggerWithUi();
app.UseAuthentication();
app.UseMiddleware<SomeMiddleware>();
app.UseMvc();
}
I need to add some additional claims AFTER the user is authenticated, but the middleware Invoke function always fires before Auth (HttpContext.User.Identity.IsAuthenticated is false).我需要在用户通过身份验证后添加一些额外的声明,但中间件调用函数总是在 Auth 之前触发(HttpContext.User.Identity.IsAuthenticated 为 false)。 But when it hits the controller the user is authenticated fine.
但是当它击中控制器时,用户的身份验证很好。
Any idea what to do here?知道在这里做什么吗? I've tried to put "app.UseAuthentication()" after calling
app.UseMiddleware
but it has no affect.我尝试在调用
app.UseMiddleware
后放置“app.UseAuthentication()”,但没有任何影响。
I'm currently using multiple Authentication schemes.我目前正在使用多种身份验证方案。 I'm not sure if that has an affect.
我不确定这是否有影响。
Yes it's possible, but instead of adding to the list of existing claims you have to add a new identity of type ClaimsIdentity
.是的,这是可能的,但是您必须添加一个
ClaimsIdentity
类型的新身份,而不是添加到现有声明列表中。
public class SomeMiddleware
{
private readonly RequestDelegate _next;
public SomeMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
if (httpContext.User != null && httpContext.User.Identity.IsAuthenticated)
{
var claims = new List<Claim>
{
new Claim("SomeClaim", "SomeValue")
};
var appIdentity = new ClaimsIdentity(claims);
httpContext.User.AddIdentity(appIdentity);
}
await _next(httpContext);
}
}
You can add another middleware immediately after the UseAuthentication()
to add claims :您可以在
UseAuthentication()
之后立即添加另一个中间件以添加声明:
app.UseAuthentication();
app.Use(async(context, next)=>{
if(context.User !=null && context.User.Identity.IsAuthenticated){
// add claims here
context.User.Claims.Append(new Claim("type-x","value-x"));
}
await next();
});
// call other middlewares
app.UseMiddleware<SomeMiddleware>();
You could write your own middleware to add new claims.您可以编写自己的中间件来添加新声明。
public class YourCustomMiddleware
{
private readonly RequestDelegate _next;
public YourCustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
if (httpContext.User != null && httpContext.User.Identity.IsAuthenticated)
{
httpContext.User.Identities.FirstOrDefault().AddClaim(new Claim("your claim", "your field"));
}
await _next(httpContext);
}
}
and in your app startup并在您的应用程序启动中
app.UseAuthentication();
app.UseMiddleware<YourCustomMiddleware>();
The preferred way for .NET Core 2.x is to use IClaimsTransformation , this has a single method TransformAsync(ClaimsPrincipal) with the note .NET Core 2.x 的首选方法是使用IClaimsTransformation ,它有一个带有注释的 TransformAsync(ClaimsPrincipal) 方法
Provides a central transformation point to change the specified principal.
提供一个中央转换点来更改指定的主体。 Note: this will be run on each AuthenticateAsync call, so its safer to return a new ClaimsPrincipal if your transformation is not idempotent.
注意:这将在每个 AuthenticateAsync 调用上运行,因此如果您的转换不是幂等的,则返回新的 ClaimsPrincipal 会更安全。
Depending on the nature of the enrichment I add the claims to the existing authenticated identity or create a new identity with and mark that as authenticated.根据扩充的性质,我将声明添加到现有的已验证身份或创建一个新身份并将其标记为已验证。 With the second idea you can make your method idempotent by checking for your custom identity before attempting the enrichment.
使用第二个想法,您可以通过在尝试丰富之前检查您的自定义身份来使您的方法具有幂等性。
It depends on what do you want to do and which scheme you use.这取决于您想做什么以及您使用哪种方案。
For example, if you use JwtBearer
then you could utilize JwtBearerOptions.Events
to handle particular events raised by the middleware.例如,如果您使用
JwtBearer
那么您可以利用JwtBearerOptions.Events
来处理中间件引发的特定事件。 You need to set that in your ConfigureServices
method of Startup
class.您需要在
Startup
类的ConfigureServices
方法中进行设置。
That would give you more granular control of what precise case you want to have your Claims added to, for example, OnTokenValidated
.这将使您能够更精细地控制您希望将 Claims 添加到哪个精确案例,例如
OnTokenValidated
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.