MVC应用程序中的User.Claims为空 [英] User.Claims Is Empty In MVC Application
问题描述
我正在将.NET Core 2.2 MVC应用程序升级到3.0。在此应用程序中,我正在使用JWT令牌向控制器进行身份验证。令牌包含多个声明,但是当我尝试通过 User.Claims
访问它们时,结果列表始终为空。
I'm working on upgrading my .NET Core 2.2 MVC application to 3.0. In this application I'm authenticating to a controller using a JWT token. The token contains several claims, but when I try to access them through User.Claims
the resulting list is always empty.
在我的 Startup.cs
中,我具有如下身份验证设置:
In my Startup.cs
I have the authentication setup like so:
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中,我可以使用类似于以下代码:
In Core 2.2 I was able to access my claims using code similar to the following:
[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
对象的声明。
However, when I migrate the same code to Core 3.0, I authenticate properly, but I get no claims for the User
object.
我错过了将其转换为3.0的步骤吗? User
是否不再自动填充信息或其他信息?
Did I miss a step in converting this to 3.0? Does User
not get automatically populated with information anymore or something?
推荐答案
使用asp.net core 3.0路由已更改为Endpoint路由。您可以通过设置 EnableEndpointRouting = false
退出。
With asp.net core 3.0 routing has changed to Endpoint routing. You can opt-out by setting EnableEndpointRouting = false
.
但是这里似乎不是这样。这意味着您在使用某些服务时必须包括某些服务,例如身份验证和授权:
But that seems not the case here. That means you'll have to include certain services when you use them, like authentication and authorization:
public void Configure(IApplicationBuilder app)
{
...
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
最重要的是,按此顺序。如此处所述:迁移启动。配置。
And most important, in that order. As documentated here: Migrate Startup.Configure.
这篇关于MVC应用程序中的User.Claims为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!