public async Task <ActionResult> Login([FromBody] Models.AuthRequest model) { Authentication.Account account = await AccountManager.FindByNameAsync(model.Email); if (account != null && await AccountManager.CheckPasswordAsync(account, model.Password)) { IList <string> accountRoles = await AccountManager.GetRolesAsync(account); List <Claim> authClaims = new List <Claim> { new Claim(ClaimTypes.Email, account.Email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; foreach (string role in accountRoles) { authClaims.Add(new Claim(ClaimTypes.Role, role)); } SymmetricSecurityKey authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppConfig["JWT:PrivateKey"])); JwtSecurityToken token = new JwtSecurityToken( issuer: AppConfig["JWT:ValidIssuer"], audience: AppConfig["JWT:ValidAudience"], expires: DateTime.Now.AddHours(3), claims: authClaims, signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256) ); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo })); } return(Unauthorized()); }
public async Task <ActionResult> Register([FromBody] Models.AuthRequest model) { Authentication.Account accountExists = await AccountManager.FindByNameAsync(model.Email); if (accountExists != null) { return(StatusCode(StatusCodes.Status500InternalServerError, new Models.AuthResponse { Status = "Error", Message = "Account already exists!" })); } Authentication.Account account = new Authentication.Account() { Email = model.Email, SecurityStamp = Guid.NewGuid().ToString(), UserName = model.Email }; IdentityResult result = await AccountManager.CreateAsync(account, model.Password); if (!result.Succeeded) { string errorMessage = "Account creation failed! Please check request details and try again."; foreach (var error in result.Errors) { errorMessage += Environment.NewLine; errorMessage += " - " + error.Description; } return(StatusCode(StatusCodes.Status500InternalServerError, new Models.AuthResponse { Status = "Error", Message = errorMessage })); } await this.SanitizeRole(model); if (await RoleManager.RoleExistsAsync(model.Role)) { await AccountManager.AddToRoleAsync(account, model.Role); } return(Ok(new Models.AuthResponse { Status = "Success", Message = "Account created successfully!" })); }