【发布时间】:2020-07-27 14:39:25
【问题描述】:
我想要不同的 JWT 认证不同的控制器方法。
Startup.cs 看起来像:
services
.AddAuthentication()
.AddJwtBearer("Schema1", options =>
{
...
// use JWT Authentication with secretKey1
var issuerSecretKey = "secretKey1";
options.TokenValidationParameters.IssuerSigningKey = new SymmetricSecurityKey(
Encoding.ASCII.GetBytes(issuerSecretKey));
})
.AddJwtBearer("Schema2", options =>
{
...
// use JWT Authentication with secretKey2
var issuerSecretKey = "secretKey2";
options.TokenValidationParameters.IssuerSigningKey = new SymmetricSecurityKey(
Encoding.ASCII.GetBytes(issuerSecretKey));
});
services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes("Schema1", "Schema2")
.Build();
});
控制器
[Authorize(AuthenticationSchemes = "Schema1")]
public ActionResult Method1(int id)
{
//some code
}
[Authorize(AuthenticationSchemes = "Schema2")]
public ActionResult Method2(int id)
{
//some code
}
之后我带着Postman,通过secretKey2用JWT执行对Method1的请求,但它成功通过了授权! 我用这个答案https://stackoverflow.com/a/49706390/11593189
secretKey1使用JWT授权Method1,secretKey2使用JWT授权Method2怎么办? 也许我应该使用其他机制,例如 Policy 或 Role?
【问题讨论】:
-
根据this github issue,认证方案是区分大小写的,尝试在Authorize Attribute中将“schema2”改为“Schema2”
-
对不起,我被封了。我在控制器中使用 Schema1 和 Schema2
标签: c# .net authentication asp.net-core jwt