app.UseAuthentication() 身份信息设置到 HttpContext.User
时间: 2024-04-18 17:33:16
浏览: 151
在 ASP.NET Core 应用程序中,`app.UseAuthentication()` 中间件会将身份[验证](https://geek.csdn.net/educolumn/0330ae9ce73d0920177833b396480304?spm=1055.2569.3001.10083)后的用户信息设置到 `HttpContext.User` 属性中。
`HttpContext.User` 属性是一个 `ClaimsPrincipal` 对象,它包含了经过身份[验证](https://geek.csdn.net/educolumn/0330ae9ce73d0920177833b396480304?spm=1055.2569.3001.10083)的用户的身份信息。`ClaimsPrincipal` 是一个包含了一系列声明(Claims)的对象,每个声明都包含了用户的某些属性或权限。
通过将身份信息设置到 `HttpContext.User` 中,你可以在请求处理过程中方便地访问用户的身份信息。例如,你可以在控制器中使用 `User` 属性来获取当前经过身份[验证](https://geek.csdn.net/educolumn/0330ae9ce73d0920177833b396480304?spm=1055.2569.3001.10083)的用户:
```csharp
[Authorize]
public class MyController : Controller
public IActionResult MyAction()
// 获取当前用户的唯一标识
[string](https://geek.csdn.net/edu/8802d631b97a4a6af1f4d0bbf8527465?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083) userId = User.FindFirstValue("userId");
// 获取当前用户的用户名
[string](https://geek.csdn.net/edu/8802d631b97a4a6af1f4d0bbf8527465?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083) username = User.Identity.Name;
// 其他操作...
return View();
在上述示例中,我们使用 `User` 属性来获取当前经过身份验证的用户。通过 `User.FindFirstValue("userId")`,我们可以获取
相关推荐

















