public async Task <IActionResult> RegisterUser([FromBody] Client.Models.Users.UserRegistrationInfo registrationInfo, [FromServices] IJwtSigningEncodingKey signingEncodingKey, CancellationToken cancellationToken) { if (registrationInfo == null) { var error = ServiceErrorResponses.BodyIsMissing("RegistrationInfo"); return(BadRequest(error)); } if (registrationInfo.Login == null || registrationInfo.Password == null) { var error = ServiceErrorResponses.NotEnoughUserData(); return(BadRequest(error)); } var creationInfo = new UserCreationInfo(registrationInfo.Login, Auth.AuthHash.GetHashPassword(registrationInfo.Password)); User user = null; try { user = await users.CreateAsync(creationInfo, cancellationToken); } catch (UserDuplicationException) { var error = ServiceErrorResponses.UserNameAlreadyExists(registrationInfo.Login); return(BadRequest(error)); } var clientUser = UserConverter.Convert(user); var claims = new Claim[] { new Claim(ClaimTypes.Name, clientUser.Login), new Claim(ClaimTypes.NameIdentifier, clientUser.Id), }; var encodedJwt = new JwtSecurityTokenHandler().WriteToken(JWT.GetJWT(claims, signingEncodingKey)); return(Ok(new AuthTokenAnswer { AccessToken = encodedJwt })); }
public async Task <IActionResult> GenerateToken([FromBody] Client.Models.Users.UserRegistrationInfo userInfo, [FromServices] IJwtSigningEncodingKey signingEncodingKey, CancellationToken cancellationToken) { if (userInfo == null) { var error = ServiceErrorResponses.BodyIsMissing("UserInfo"); return(BadRequest(error)); } if (userInfo.Login == null || userInfo.Password == null) { var error = ServiceErrorResponses.NotEnoughUserData(); return(BadRequest(error)); } User user; try { user = await users.GetAsync(userInfo.Login, cancellationToken); } catch (UserNotFoundException) { var error = ServiceErrorResponses.UserNotFound(); return(BadRequest(error)); } var clientUser = UserConverter.Convert(user); var claims = new Claim[] { new Claim(ClaimTypes.Name, clientUser.Login), new Claim(ClaimTypes.NameIdentifier, clientUser.Id), }; var encodedJwt = new JwtSecurityTokenHandler().WriteToken(JWT.GetJWT(claims, signingEncodingKey)); return(Ok(new AuthTokenAnswer { AccessToken = encodedJwt })); }
public ActionResult SignIn() { string userName = Request.Form["userName"]; string password = Request.Form["password"]; var tokenResponse = JWT.GetJWT(userName, password); if (tokenResponse != null) { Response.ContentType = "application/json"; //await HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); return(Json(tokenResponse, new JsonSerializerSettings { Formatting = Formatting.Indented })); } else { return(Unauthorized()); } }