Is there a way to add claims in an ASP.NET Core middleware after Authentication?

后端 未结 5 1627
梦谈多话
梦谈多话 2021-02-04 02:30

I have this in my startup:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperE         


        
相关标签:
5条回答
  • 2021-02-04 03:12

    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. You need to set that in your ConfigureServices method of Startup class.

    That would give you more granular control of what precise case you want to have your Claims added to, for example, OnTokenValidated.

    0 讨论(0)
  • 2021-02-04 03:14

    The preferred way for .NET Core 2.x is to use IClaimsTransformation, this has a single method TransformAsync(ClaimsPrincipal) with the note

    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.

    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.

    0 讨论(0)
  • 2021-02-04 03:15

    Yes it's possible, but instead of adding to the list of existing claims you have to add a new identity of type 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);
        }
    }
    
    0 讨论(0)
  • 2021-02-04 03:20

    You can add another middleware immediately after the UseAuthentication() to add claims :

    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>();
    
    0 讨论(0)
  • 2021-02-04 03:32

    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>();
    
    0 讨论(0)
提交回复
热议问题