简体   繁体   English

_userManager.FindByEmailAsync(User.FindFirstValue(ClaimTypes.Email)) 返回 null

[英]_userManager.FindByEmailAsync(User.FindFirstValue(ClaimTypes.Email)) returns null

I am having an issue with Claims not populating with ClaimsPrinciple after creating a JWT. I am using ASP.NET Core 6 on VS 2022. The issue raised after configuring identity to include Roles and RolesUsers.创建 JWT 后,我遇到了 Claims 未填充 ClaimsPrinciple 的问题。我在 VS 2022 上使用 ASP.NET Core 6。将身份配置为包含 Roles 和 RolesUsers 后引发的问题。 I had no issues prior to including these 2 identity tables from the automated generated ones from IdentityModel.在从 IdentityModel 自动生成的身份表中包含这两个身份表之前,我没有遇到任何问题。

now on creation, I show no errors and receive the JWT token without any issues, but afterwards when I try to authorize the user that log in the ClaimIdentity does not propagate and errors on _userManager.FindByEmailAsync(User.FindFirstValue(ClaimTypes.Email)) showing null.现在在创建时,我没有显示任何错误并且没有任何问题地收到 JWT 令牌,但是之后当我尝试授权用户登录时,ClaimIdentity 不会传播并且 _userManager.FindByEmailAsync(User.FindFirstValue(ClaimTypes.Email)) 上出现错误显示 null。

Here is some code to show the current state of the project.这是一些代码来显示项目的当前 state。

First is the Method that handles the validation for login users.首先是处理登录用户验证的方法。

       [Authorize]
        [HttpGet]
        public async Task<ActionResult<UserDto>> GetCurrentUser()
        {

            // Null Exception Error
            var user = await _userManager.FindByEmailAsync(User.FindFirstValue(ClaimTypes.Email));

            return CreateUserObject(user);
        }

        UserDto CreateUserObject( AppUser user )
        {
            return new UserDto
            {
                DisplayName = user.DisplayName,
                Image = null,
                Token = _tokenService.CreateToken(user),
                Username = user.UserName
            };
        }

This is my Token Service that handles creating the JWT token from users that Register or Login.这是我的令牌服务,用于处理从注册或登录的用户创建 JWT 令牌。

    public class TokenService
    {
        private readonly IConfiguration _config;

        public TokenService(IConfiguration config)
        {
            _config = config;
        }

        public string CreateToken(AppUser user)
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(ClaimTypes.Email, user.Email)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["TokenKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),
                Expires = DateTime.Now.AddDays(7.0),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return tokenHandler.WriteToken(token);
        }
    }

This is what I changed prior to having this issue in my IdentityServiceExtension Class.这是我在 IdentityServiceExtension Class 中出现此问题之前所做的更改。

public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration config)
        {
            services.AddIdentity<AppUser, AppRole>(opt => //Changed AddIdentityCore to AddIdentity to apply AppUser & AppRole
            {
                opt.Password.RequireNonAlphanumeric = false;
            })
                .AddEntityFrameworkStores<DataContext>()
                .AddSignInManager<SignInManager<AppUser>>()
                .AddRoleManager<RoleManager<AppRole>>(); //Added Role Manager for Roles to loaded.


            var Key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["TokenKey"]));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(opt =>
                {
                    opt.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = Key,
                        ValidateIssuer = false,
                        ValidateAudience = false
                    };
                });

            services.AddScoped<TokenService>();

            // Added Roles to Policy
            services.AddAuthorization(opt =>
            {
                opt.AddPolicy("Verified", pol => 
                    pol.RequireRole("User", "Staff", "Admin", "Guest"));
                opt.AddPolicy("Restricted", pol =>
                    pol.RequireRole("User", "Staff", "Admin"));
                opt.AddPolicy("EmployeeAccess", pol =>
                    pol.RequireRole("Staff", "Admin"));
                opt.AddPolicy("ManagerAccess", pol =>
                    pol.RequireRole("Admin"));
            });
            //////////////////////

            return services;
        }

Hopefully this is enough information to help me with this issue.希望这些信息足以帮助我解决这个问题。 I have searched all over online and the resolutions I have seen does not match to my particular issue to solve the problem.我在网上到处搜索,看到的解决方案与我解决问题的特定问题不符。

I surprisingly found the issue, so the reason I was having errors was due to not configuring Identity to handle all Identity Models.我出乎意料地发现了这个问题,所以我出错的原因是没有配置身份来处理所有身份模型。 Prior to my change, I only handled users, but by adding roles and roleusers I had to handle all of Identity Model to prevent losing the claims.在我更改之前,我只处理用户,但通过添加角色和角色用户,我必须处理所有身份 Model 以防止丢失声明。 Due to this fact, I had to install another Microsoft Package,Microsoft.AspNetCore.Identity.UI, to gain access to the Identity Helper Method (.AddDefaultIdentity()) to configure the generated identity tables.由于这个事实,我不得不安装另一个 Microsoft Package,Microsoft.AspNetCore.Identity.UI,以访问身份助手方法 (.AddDefaultIdentity()) 来配置生成的身份表。 Once added, Identity was fully configured and the issue was resolved.添加后,Identity 已完全配置,问题已解决。 I hope anyone else that need help can use this as a possible solution.我希望任何其他需要帮助的人都可以将此作为可能的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM