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 Register([FromBody] GetAuthorDto authorDto) { // map dto to entity var author = _mapper.Map <Author>(authorDto); try { // save _authorService.Create(author, authorDto.Password); return(Ok()); } catch (AppException ex) { // return error message if there was an exception return(BadRequest(ex.Message)); } }
public IActionResult Update(int id, [FromBody] GetAuthorDto authorDto) { // map dto to entity and set id var author = _mapper.Map <Author>(authorDto); author.AuthorId = id; try { // save _authorService.Update(author, authorDto.Password); return(Ok()); } catch (AppException ex) { // return error message if there was an exception return(BadRequest(ex.Message)); } }