首页 > 解决方案 > 验证由 .net 核心微服务创建的 JWT

问题描述

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

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

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

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

标签: authenticationasp.net-web-apijwtauthorizationmicroservices

解决方案


为了实现这一点,我做了两件事。首先,在 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 应用程序中的令牌。


推荐阅读