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

后端 未结 5 1626
梦谈多话
梦谈多话 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: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();
    

提交回复
热议问题