Chr*_*ell 8 c# asp.net-mvc .net-core
我正在将.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"
};
});
}
}
Run Code Online (Sandbox Code Playgroud)
在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 //
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我将相同的代码迁移到Core 3.0时,我进行了正确的身份验证,但是没有得到该User
对象的声明。
我是否错过了将其转换为3.0的步骤?是否User
不再自动填充信息或其他信息?
小智 2
看来用户根本没有经过身份验证。
在 asp.net core 3.0 中,路由已更改为 Endpoint 路由。您可以通过设置选择退出EnableEndpointRouting = false
。
但这里的情况似乎并非如此。这意味着您在使用它们时必须包含某些服务,例如身份验证和授权:
public void Configure(IApplicationBuilder app)
{
...
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
Run Code Online (Sandbox Code Playgroud)
最重要的是,按照这个顺序。如此处所述:迁移 Startup.Configure。
归档时间: |
|
查看次数: |
111 次 |
最近记录: |