c# - 将 IdentityUser 添加到 HttpContext.User
问题描述
我正在使用 .NET Core 3.0 。我正在尝试通过 API 密钥授权对用户进行身份验证。我创建了一个中间件,每次调用控制器端点时都会调用它。我可以对用户进行身份验证并获取声明,但我无法将HttpContext.User
对象设置为使用此身份。
public async System.Threading.Tasks.Task Invoke(HttpContext context, Services.AuthenticationService authenticationService, UserManager<IdentityUser> userManager, SignInManager<IdentityUser> _signInManager)
{
if (!context.Request.Path.ToString().Contains("Token") && context.Request.Path.StartsWithSegments(new PathString("/api")))
{
var userKey = context.Request.Headers["user-key"];
// Register the user and its claims to the session
var user = authenticationService.GetUserFromToken(userKey);
var claims = await userManager.GetClaimsAsync(user);
if (claims == null)
{
context.Response.StatusCode = 401; //UnAuthorized
await context.Response.WriteAsync("Claims not found for user");
return;
}
var claimsIdentity = new ClaimsIdentity(IdentityConstants.ApplicationScheme);
claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
claimsIdentity.AddClaims(claims);
context.User.AddIdentity(claimsIdentity);
await _signInManager.Context.SignInAsync(IdentityConstants.ApplicationScheme, new ClaimsPrincipal(claimsIdentity));
}
await _next.Invoke(context);
}
当我签HttpContext.User
入我的控制器时,主要身份对象没有任何信息。在身份对象中有两个身份。第二个身份具有我在中间件中设置的声明和用户名。
如何将主要身份设置为唯一身份?_signInManager
代码实际上并没有做任何事情,HttpContext.User
无论有没有它,我都会在对象中得到相同的结果。
解决方案
推荐阅读
- python - 看到 Cython 没有加速
- django - Django REST Serializer 使所有字段都允许 null 或不需要
- python - 使用 selenium 查找嵌套在“concat(”XPATH 中的元素
- docker - Docker:COPY 是否支持可变目标?
- python - 使用 -xpath -selenium -python 访问标签的内容
- vue.js - 在 SSR 和代理中使用 nuxt 的 cors 问题
- ios - 无法使用 Objective-C 在 iOS 上渲染相机预览
- android - 按下项目时打开新活动
- python - 将图像灰度像素值转换为 alpha 值
- python - 如何抑制spyder中的多个绘图弹出?