ASP.NET Core中的HttpContext.User属性始终为空的问题通常是由于身份验证和授权配置不正确引起的。下面是一些可能的解决方法:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "your_issuer",
ValidAudience = "your_audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"))
};
});
services.AddAuthorization();
app.UseAuthentication();
app.UseAuthorization();
如果使用了自定义身份验证方案,请确保在调用UseAuthentication方法之前添加AddAuthentication方法的配置。
确保在登录或验证用户身份后设置了正确的用户声明。例如,在登录控制器或身份验证过滤器中,使用以下代码设置用户声明:
var claims = new List
{
new Claim(ClaimTypes.Name, "username"),
new Claim(ClaimTypes.Role, "role")
};
var identity = new ClaimsIdentity(claims, "AuthenticationScheme");
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync("AuthenticationScheme", principal);
如果仍然存在问题,可以尝试使用调试器检查中间件配置和用户声明设置的正确性,并根据具体情况进行调试和排查。