此问题可能是因为在服务配置中设置了身份验证方案,但在API控制器中并没有对该方案进行身份验证。如果使用基于声明的身份验证方案,则必须确保控制器中包含[Authorize]属性,并且可以使用HttpContext.User.Claims属性获取用户声明。 以下是一个示例控制器,该控制器需要基于声明的身份验证方案,并使用User.Identity.Name属性获取登录用户的用户名。
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[ApiController]
[Route("[controller]")]
public class UserController : ControllerBase
{
[HttpGet("profile")]
public IActionResult GetProfile()
{
var username = User.Identity.Name;
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
// other logic to retrieve user profile
return Ok();
}
}