【发布时间】:2018-06-02 17:56:15
【问题描述】:
我有一个带有 cookie 和 jwt 身份验证方案的应用程序。这是ConfigureServices 代码:
var authTokenSettings = configuration.GetSection(nameof(TokenProviderSettings)).Get<TokenProviderSettings>();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddCookie(authSection.AuthenticationScheme, u =>
{
u.Cookie.Name = authSection.AuthCookieName;
u.LoginPath = new PathString(authSection.LoginPath);
u.AccessDeniedPath = "/Home/Index";
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = authTokenSettings.Issuer,
ValidateAudience = true,
ValidAudience = authTokenSettings.Audience,
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(authTokenSettings.Key)),
ValidateIssuerSigningKey = true,
};
});
现在我需要在一种方法上使用 cookie 方案,在另一种方法上使用 jwt。我已经添加了适当的属性
([Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)])
但是这些属性被忽略了,使用默认方案。如果我没有指定默认方案,我会得到这个异常:
System.InvalidOperationException: 没有 authenticationScheme 指定,但没有找到 DefaultChallengeScheme。
代码有什么问题?
【问题讨论】:
-
忽略属性是什么意思?您将 Jwt 指定为 Authorize 属性中的方案,这 也是 根据您的配置的默认值。所以当然你会得到“默认”方案。 – 您不能单独使用 cookie 身份验证,因为它不能单独挑战。它将质询请求传递给默认质询方案,因此使用您的配置,您将继续运行 Jwt 身份验证。
-
我有带有 cookie 身份验证的应用程序,并为 2 种方法添加 jwt 之一。如果我将 cookie 身份验证方案设置为默认值 - jwt 身份验证将被忽略
-
你确定它被忽略了吗?还是只是它在您的默认值之后运行?
标签: authentication cookies asp.net-core jwt