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

时间:2018-11-16 23:27:57

标签: asp.net-mvc asp.net-core-2.0 asp.net-core-webapi .net-security

我的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令牌?

1 个答案:

答案 0 :(得分:1)

是的,Asp.Net核心中间件将验证JWT令牌。确保您正在配置JWT承载选项和令牌验证参数,以便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

            };
        });