【发布时间】:2019-10-17 17:22:07
【问题描述】:
我正在将我的 .NET Core 2.2 MVC 应用程序升级到 3.0。在这个应用程序中,我使用 JWT 令牌对控制器进行身份验证。该令牌包含多个声明,但当我尝试通过 User.Claims 访问它们时,结果列表始终为空。
在我的Startup.cs 中,我的身份验证设置如下:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Code removed for clarity //
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = JwtManager.Issuer,
ValidAudience = "MyAudience",
IssuerSigningKey = "MySigningKey"
};
});
}
}
在 Core 2.2 中,我可以使用类似于以下的代码访问我的声明:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class MyController : Controller
{
[HttpGet("MyController/Action")]
public ActionResult<Aggregate[]> GetAction()
{
var username = User.FindFirstValue("MyUsernameClaim");
if (username == null)
{
return Forbid();
}
// Do Stuff //
}
}
但是,当我将相同的代码迁移到 Core 3.0 时,我正确地进行了身份验证,但我没有收到 User 对象的声明。
我是否错过了将其转换为 3.0 的步骤? User 不会再自动填充信息吗?
【问题讨论】:
-
您能否确认用户已通过身份验证?我看不到图像,但
User.Identity.IsAuthenticated似乎是错误的。如果是这样,那么这可能与 AuthenticationScheme 有关。 -
你是如何配置路由的?您是否在 UseEndpoints 之前按顺序添加了 UseRouting、UseAuthentication 和 UseAuthorization?你能展示那段代码吗?
-
@RuardvanElburg 我将
UseEndpoints移动到Configure方法的末尾并修复了问题。天哪,我无法相信这么简单的事情让我花费了令人尴尬的时间。如果您想将其发布为答案,我会接受。
标签: c# asp.net-mvc .net-core