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

后端 未结 5 1634
梦谈多话
梦谈多话 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: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
                {
                    new Claim("SomeClaim", "SomeValue")
                };
    
                var appIdentity = new ClaimsIdentity(claims);
                httpContext.User.AddIdentity(appIdentity);                
            }
    
            await _next(httpContext);
        }
    }
    

提交回复
热议问题