我需要在 asp.net core 2 REST API 中验证 JWT 令牌吗?

Do I need to validate JWT tokens in asp.net core 2 REST API?

我的 asp.net 核心 REST API 配置中有以下代码:

services
    .AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; })
    .AddJwtBearer(options =>
        {
            options.Authority = "https://login.microsoftonline.com/XXXTenantIDXXX";
            options.Audience = "XXXX clientId XXXX";
        });

services.AddMvc(o =>
    {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        o.Filters.Add(new AuthorizeFilter(policy));

它验证请求。它工作正常。

我担心并担心来自租户中其他 AAD 应用程序的 jwt 令牌伪造或 jwt 令牌。

我希望上面的代码向 asp.net 核心身份验证提供所有信息,以验证 jwt 是否有效并且其受众是正确的 AAD 应用程序。

我想在这里确认我的期望,问我是否需要额外的逻辑(代码)来验证 JWT 令牌?

是的,Asp.Net 核心中间件验证 JWT 令牌。确保您正在配置 JWT Bearer 选项和令牌验证参数,以便 Asp.Net 核心中间件对其进行验证。

例如:

      services.AddAuthentication(auth =>
        {
            auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {               
            options.ClaimsIssuer = jwtAuthSettings.ValidIssuer;//Your issuer
            options.IncludeErrorDetails = true;
            options.RequireHttpsMetadata = true;
            options.SaveToken = true;
            options.Validate(JwtBearerDefaults.AuthenticationScheme);
            options.TokenValidationParameters = new TokenValidationParameters()
            {
                ClockSkew = TimeSpan.FromMinutes(30),
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = jwtAuthSettings.ValidIssuer, //Your issuer
                ValidAudience = jwtAuthSettings.ValidAudience,//Your Audience
                IssuerSigningKey = jwtAuthSettings.SymmetricSecurityKey, //Your Key
                NameClaimType = ClaimTypes.NameIdentifier,
                RequireSignedTokens = true,
                RequireExpirationTime = true

            };
        });