【发布时间】:2018-01-30 03:51:40
【问题描述】:
我使用 ASP.NET Core 2.0 应用程序 (Web API) 作为 JWT 颁发者来生成移动应用程序可使用的令牌。不幸的是,这个令牌不能被一个控制器验证,而可以被另一个控制器验证(在同一个 asp.net core 2.0 应用程序中使用相同的验证设置)。
所以我有一个有效且可以解码的令牌,具有所有必需的声明和时间戳。但是一个端点接受它,而另一个给我 401 错误和调试输出:
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:信息: 用户授权失败:(null)。
[40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed for user: (null).
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed for user: (null).
[40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.ChallengeResult:Information: Executing ChallengeResult with authentication schemes ().
[40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
Executing ChallengeResult with authentication schemes ().
[40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[12]
AuthenticationScheme: Bearer was challenged.
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:Information: AuthenticationScheme: Bearer was challenged.
[40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action MyController.Get (WebApi) in 72.105ms
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action MyController.Get (WebApi) in 72.105ms
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 271.077ms 401
[40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 271.077ms 401
我的验证设置如下:
var secretKey = Configuration["Authentication:OAuth:IssuerSigningKey"];
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = Configuration["Authentication:OAuth:Issuer"],
ValidateAudience = true,
ValidAudience = Configuration["Authentication:OAuth:Audience"],
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
};
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = tokenValidationParameters;
});
这两个端点是相同的,只是存在于不同的控制器中,都标有Authorize 属性。
这怎么可能?
【问题讨论】:
-
+1 您的详细代码引起了我对
ClockSkew的注意,这让我了解了一个单独的问题,即我的令牌似乎没有过期。
标签: c# asp.net-core asp.net-core-webapi bearer-token asp.net-core-identity