private async Task CreateUser(string name, string email, string password, bool isAdmin) { var user = await userManager.FindUserByNameAsync(name); if (user == null) { user = new User() { UserName = name, Email = email }; var userResult = await userManager.CreateAsync(user, password); if (!userResult.Succeeded) { throw new InvalidOperationException("Failed to build user and roles"); } if (isAdmin) { var roleResult = await userManager.AddToRoleAsync(user, SystemRoles.Admin); var claimResult = await userManager.AddClaimAsync(user, new System.Security.Claims.Claim(SystemClaims.IsAdmin, "true", System.Security.Claims.ClaimValueTypes.Boolean)); if (!roleResult.Succeeded || !claimResult.Succeeded) { throw new InvalidOperationException("Failed to build user and roles"); } } } }
public async Task <UserModel> LoadUserByName(string userName) { var entity = await userManager.FindUserByNameAsync(userName); if (entity == null) { return(null); } return(new UserModel() { Id = entity.Id, Email = entity.Email, Name = entity.UserName }); }
public async Task <TokenGeneratorResult> GenerateToken(string userName, string password) { var user = await userManager.FindUserByNameAsync(userName); if (user != null) { if (await userManager.ValidatePasswordForUser(user, password)) { var userClaims = await claimsProvider.GetClaimsAsync(user.Id); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Email, user.Email), new Claim("id", user.Id.ToString()) }.Union(userClaims); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authConfig.TokenKey)); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: authConfig.Issuer, audience: authConfig.Audience, claims: claims, expires: DateTime.UtcNow.AddMinutes(authConfig.TokenValidInMinutes), signingCredentials: credentials); var tokenString = new JwtSecurityTokenHandler().WriteToken(token); return(new TokenGeneratorResult { Token = new TokenModel(tokenString, token.ValidTo) }); } else { throw new ArgumentException($"Password for email {userName} is invalid."); } } else { throw new ArgumentException($"User for email {userName} not found"); } }