首页 > 解决方案 > 将 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无论有没有它,我都会在对象中得到相同的结果。

标签: c#asp.net-core

解决方案


推荐阅读