简体   繁体   English

有没有办法在身份验证后在 ASP.NET Core 中间件中添加声明?

[英]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.

相关问题 ASP.NET Core 2.0身份验证中间件 - ASP.NET Core 2.0 authentication middleware 身份验证后,如何在ASP.Net Core中由OpenIdConnect中间件生成的身份验证cookie中添加自定义声明? - How do I add a custom claim to authentication cookie generated by OpenIdConnect middleware in ASP.Net Core after authentication? 通过ASP.NET核心身份中的角色声明进行JWT身份验证 - JWT Authentication by role claims in ASP.NET core Identity 如何使用 Windows 身份验证在 ASP.NET Core 5 中操作声明 - How to manipulate Claims in ASP.NET Core 5 with Windows authentication ASP.NET CORE中的自定义身份验证和更新声明 - Custom Authentication & Update Claims in ASP.NET CORE 从 ASP.NET 核心 MVC 上的 JWT 身份验证中检索声明 - Retrieve claims from JWT authentication on ASP.NET Core MVC ASP.NET 核心 JWT 身份验证更改声明(子) - ASP.NET Core JWT authentication changes Claims (sub) 如何在ASP.NET Core 2中使用依赖注入的OIDC登录Azure AD后添加自己的声明? - How to add own claims after logging in to Azure AD with OIDC in ASP.NET Core 2 with dependency injection? ASP.NET Core Identity - 如何在初始登录后添加新声明 - ASP.NET Core Identity - How to add new claims after initial login asp.net核心如何向User添加声明 - asp.net core how to add claims to User
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM