public IActionResult Authenticate([FromBody] GetAuthorDto authorDto) { var author = _authorService.Authenticate(authorDto.Username, authorDto.Password); if (author == null) { return(BadRequest("Authorname or password is incorrect")); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, author.AuthorId.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); // return basic author info (without password) and token to store client side return(Ok(new { Id = author.AuthorId, author.Username, author.FirstName, author.LastName, Token = tokenString })); }
public IActionResult Authenticate([FromBody] AuthDto authDto) { var author = _authorService.Authenticate(authDto.Username, authDto.Password); if (author == null) { var errorMessage = "Username or password is incorrect."; return(Unauthorized(new ErrorResponseDto { InternalErrorMessage = errorMessage, DisplayErrorMessage = errorMessage })); } else if (!author.IsDeleted.HasValue || author.IsDeleted.Value) { var errorMessage = "This username has been permanently deactiviated."; return(Unauthorized(new ErrorResponseDto { InternalErrorMessage = errorMessage, DisplayErrorMessage = errorMessage })); } else if (!author.IsLocked.HasValue || author.IsLocked.Value) { var errorMessage = "This user has been locked. Please contact system administrator."; return(Unauthorized(new ErrorResponseDto { InternalErrorMessage = errorMessage, DisplayErrorMessage = errorMessage })); } var tokenExpiration = DateTime.Now.AddDays(7); var refreshTokenExpiration = DateTime.Now.AddDays(30); var tokenHandler = new JwtSecurityTokenHandler(); var keyBytes = Encoding.ASCII.GetBytes(_authConfig.Secret); var securityKey = new SymmetricSecurityKey(keyBytes); var tokenDescriptor = new SecurityTokenDescriptor { Issuer = _authConfig.Issuer, Audience = _authConfig.Audience, Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, author.AuthorId.ToString()), new Claim(ClaimTypes.Expiration, tokenExpiration.ToString()) }), Expires = tokenExpiration, SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature), }; var token = tokenHandler.CreateToken(tokenDescriptor); var responseDto = _mapper.Map <AuthResponseDto>(author); responseDto.Token = tokenHandler.WriteToken(token); responseDto.TokenExpirationDate = tokenExpiration; responseDto.RefreshTokenExpirationDate = refreshTokenExpiration; responseDto.RefreshToken = _authorService.EncodeRefreshToken(author.Username, refreshTokenExpiration); return(Ok(responseDto)); }