JWTBearer身份验证:一段时间后,JWTBearer身份验证将无法工作

时间:2019-08-07 13:11:55

标签: c# authentication asp.net-core bearer-token

我们使用Azure托管的ASP.NET Core 2.2服务。共有三种不同的身份验证类型:使用的OpenId,JWTBearer和Cookies。

服务的一部分是API,应用程序可以在其中发送请求并使用承载令牌进行身份验证。

到目前为止,一切正常:我们的应用程序将请求发送到服务的API,并且身份验证正常。在部署一段时间(1-2天)后,我们注意到JWTBearer-Authentication不再起作用。

因此,我们提高了日志级别,以从Azure Application Insights中获取更多信息。日志向我们显示了JWTBearer将不再受到挑战,而OpenId将我们重定向到登录页面。当我们重新部署服务时,一切正常,直到接下来的1-2天。

现在,我找到了一种解决该问题的方法,但是我并没有真正理解帮助修复JWTBearer身份验证的重大更改。

有人有主意吗?

身份验证的旧版本:

string audience = "https://test.test";
string azureActiveDirectoryInstance = "https://login.microsoftonline.com/";
string tenant = "DummyText";
string authority = $"{azureActiveDirectoryInstance}{tenant}";

services.AddAuthentication(sharedOptions =>
{
    sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
    .AddAzureAd(options => objConfiguration.Bind("Authentication:AzureAd", options))
    .AddCookie(cookieOptions =>
    {
        cookieOptions.ExpireTimeSpan = new TimeSpan(7, 0, 0);
    })
    .AddJwtBearer(jwt =>
    {
        jwt.Audience = audience;
        jwt.Authority = authority;

        jwt.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateLifetime = true,
            ValidAudience = audience,
            ClockSkew = TimeSpan.Zero,
        };
    }
);
}

身份验证的新版本:

services.AddAuthentication(sharedOptions =>
{
    sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
    .AddAzureAd(options => objConfiguration.Bind("Authentication:AzureAd", options))
    .AddCookie(cookieOptions =>
    {
        cookieOptions.ExpireTimeSpan = new TimeSpan(7, 0, 0);
    })
    .AddJwtBearer(jwt =>
    {
        jwt.Audience = audience;
        jwt.Authority = authority;

        jwt.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateLifetime = true,
            ValidAudience = audience,
            ValidateAudience = true,
            ValidateIssuer = true,
            RequireExpirationTime = true,
            ClockSkew = TimeSpan.Zero,
        };
    }
);
}

我更改了DefaultScheme和DefaultChallengeScheme,并使用了TokenValidationParameters中的其他一些属性。

我还要更改的是AuthorizationPolicy,来自:

AuthorizationPolicy policy = new AuthorizationPolicyBuilder()
                        .RequireAuthenticatedUser()
                        .Build();

AuthorizationPolicy policy = new AuthorizationPolicyBuilder(new[] { CookieAuthenticationDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme })
                        .RequireAuthenticatedUser()
                        .Build();

0 个答案:

没有答案