【问题标题】:Validate JWT created by a .net core microservice验证由 .net 核心微服务创建的 JWT
【发布时间】:2021-03-24 15:11:00
【问题描述】:

我在 docker 中运行了一些 .net 核心 Web API 微服务。

例如:目录 API、邮政编码 API、结帐 API。

我创建了另一个验证电子邮件和密码以生成 JWT 令牌的微服务。

有没有办法在其他服务中检查此令牌的凭据,例如在目录 API 中?

【问题讨论】:

    标签: authentication asp.net-web-api jwt authorization microservices


    【解决方案1】:

    为了实现这一点,我做了两件事。首先,我在 Startup.cs 中添加了这段代码:

        public static IServiceCollection AddCustomAuthentication(this IServiceCollection services)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    // -> next three lines: avoid to check de signature key (just the auth app, the issuer, has the key)
                    ValidateIssuerSigningKey = false,
                    RequireSignedTokens = false,
                    SignatureValidator = (string token, TokenValidationParameters parameters) => new JwtSecurityToken(token),
    
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateActor = false,
                    ValidateLifetime = true  // -> even avoiding the signature check, the token expiration has to be checked
                };
            });
    
            return services;
        }
    

    有了这段代码,在控制器中,我可以在没有签名检查的情况下验证令牌,只需使用 [Authorize]

    第二步,当我需要检查签名时,我创建了[AuthorizeOnJwtSource]属性:

    public class AuthorizeOnJwtSourceAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter
    {
        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            if (context.HttpContext.User.Identity.IsAuthenticated) // -> first, we need to check if we have some toeken
            {
                var authorizationService = context.HttpContext.RequestServices.GetRequiredService<AuthorizationService>();
    
                string token = context.HttpContext.Request.Headers["Authorization"];
                bool isTokenValid = await authorizationService.IsTokenValid(token);
    
                if(!isTokenValid)
                    context.Result = new UnauthorizedResult();
            }
        }
    }
    

    AuthorizationService 使用 HttpClient 来验证 isser Web 应用中的令牌。

    【讨论】:

      猜你喜欢
      • 2023-01-30
      • 2021-08-13
      • 1970-01-01
      • 2023-04-11
      • 2019-06-23
      • 2017-12-23
      • 2017-05-13
      • 2016-11-02
      • 2020-07-26
      相关资源
      最近更新 更多