private void InitializeUsers() { if (_userManager.Users.Count <WapUser>().Equals(0)) { var manager = new WapUser() { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true, FirstName = "Jacob", LastName = "Jones", IsActive = true }; _userManager.CreateAsync(manager, "Asdfjkl!1").Wait(); _userManager.AddToRoleAsync(manager, "Manager").Wait(); var agent = new WapUser() { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true, FirstName = "Janet", LastName = "Roberts", IsActive = true }; _userManager.CreateAsync(agent, "Asdfjkl!1").Wait(); _userManager.AddToRoleAsync(agent, "Agent").Wait(); var manager2 = new WapUser() { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true, FirstName = "Jacob", LastName = "Johnson", IsActive = true }; _userManager.CreateAsync(manager2, "Asdfjkl!1").Wait(); _userManager.AddToRoleAsync(manager2, "Manager").Wait(); var agent2 = new WapUser() { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true, FirstName = "Janet", LastName = "Robertson", IsActive = true }; _userManager.CreateAsync(agent2, "Asdfjkl!1").Wait(); _userManager.AddToRoleAsync(agent2, "Agent").Wait(); } }
public async Task <IActionResult> Register(UserRegistration userRegistration) { WapUser newUser = Mapper.Map <WapUser>(userRegistration); try { var createResult = await _userManager.CreateAsync(newUser, userRegistration.Password); if (!createResult.Succeeded) { var appEx = new WapException("Unable to register user."); createResult.Errors.ToList().ForEach(error => appEx.Details.Add(error.Description)); throw appEx; } return(Ok()); } catch (WapException e) { return(BadRequest(e.AsViewModel())); } }
private string CreateToken(WapUser authenticatedUser, IList <string> roles) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.UTF8.GetBytes(_configuration["Tokens:Key"]); var subjectClaims = new List <Claim>() { new Claim(ClaimTypes.Name, authenticatedUser.UserName) }; subjectClaims.AddRange(roles.Select(role => new Claim(ClaimsIdentity.DefaultRoleClaimType, role))); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(subjectClaims), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return(tokenHandler.WriteToken(token)); }