【问题标题】:Add claims using JWT bearer in ASP.NET Core在 ASP.NET Core 中使用 JWT 承载添加声明
【发布时间】:2022-01-07 06:05:55
【问题描述】:

我正在使用AddJwtBearer 在我的应用程序中使用 OAuth/OpenId 身份验证机制。我的需要之一是在用户登录(或令牌刷新)后添加特定声明。

目前,我正在使用OnTokenValidated 事件,但问题是每个请求都会调用它,并且当我调用数据库来检索我想要添加的声明时,这很烦人。尤其是现在我需要添加另一个需要更多时间从数据库中检索的声明。

我正在寻找一种仅在身份验证后添加自定义声明的方法,以避免为每个请求调用数据库。

【问题讨论】:

    标签: asp.net-core claims-based-identity


    【解决方案1】:

    我正在寻找的是一种仅在身份验证后添加自定义声明的方法

    可以使用认证中间件后调用的中间件:

    UserClaimsMiddleware.cs:

    public class UserClaimsMiddleware
    {
        private readonly RequestDelegate _next;
    
        public UserClaimsMiddleware(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);
            }
        }
    }
    
    public static class UserClaimsMiddlewareExtensions
    {
        public static IApplicationBuilder UseUserClaims(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<UserClaimsMiddleware>();
        }
    }
    

    并在Startup.csConfigure函数中注册中间件:

    app.UseAuthentication();
    app.UseUserClaims();
    app.UseMvc();
    

    避免为每个请求调用数据库。

    当服务器端获取带有令牌的 API 调用时,AddJwtBearer 将解码令牌、验证令牌并使用户经过身份验证,您可以在 OnTokenValidated 或自定义中间件中添加新的声明。但除非您在每个请求中添加声明,否则声明不会在下一次 api 调用中持续存在。

    【讨论】:

    • 嗨,目标基本上是在令牌发送到前端应用程序之前向令牌添加声明,这样,新声明将始终存在于令牌中,我不需要每次都取数据。如果我正确理解您的解释,中间件只是与 OnTokenValidated 不同的技术,但会产生相同的效果?
    • @ssougnez,是的,您应该向令牌添加声明。否则,您需要在每个请求上添加声明。
    • 我现在会尝试中间件,但您能否确认中间件会针对每个请求运行,所以它不会解决问题。而且由于ADFD无法检索我需要添加的声明,因此基本上没有解决方案将声明添加到令牌中一次?
    • 您应该在颁发令牌时添加对令牌的声明。这取决于您使用的身份提供者。此链接可能会有所帮助:stackoverflow.com/a/49202715/5751404
    猜你喜欢
    • 2018-05-08
    • 2017-03-07
    • 2019-04-14
    • 1970-01-01
    • 2019-09-30
    • 2023-03-10
    • 2023-03-23
    • 2019-04-15
    • 2018-05-20
    相关资源
    最近更新 更多