Last active
November 18, 2020 21:52
-
-
Save vaygeth89/e7665dbb33129be18388da277782e976 to your computer and use it in GitHub Desktop.
tutorial-dotnet-JWTProtectedAPI SignUp() Action
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Rest of the AccountController | |
[HttpPost] | |
[Route("sign-up")] | |
public async Task<ActionResult> SignUp(SignUpData signUpData) | |
{ | |
try | |
{ | |
//Todo add your business validation here | |
//! You may want to edit catched exceptions block to handle failed scenarios | |
IdentityUser user = new IdentityUser() | |
{ | |
Email = signUpData.Email, | |
UserName = signUpData.Username, | |
}; | |
IdentityResult identityResult = await _userManager.CreateAsync(user, signUpData.Password); | |
if (identityResult.Succeeded) | |
{ | |
string JWTToken = GenerateJWTToken(user); | |
return Ok(new | |
{ | |
Token = JWTToken | |
}); | |
} | |
return BadRequest(new | |
{ | |
Message = identityResult.Errors | |
}); | |
} | |
catch (System.Exception error) | |
{ | |
return BadRequest(new | |
{ | |
message = error.Message | |
}); | |
} | |
} | |
//Method responsible for generating JWT token based on user | |
private string GenerateJWTToken(IdentityUser user) | |
{ | |
var tokenHandler = new JwtSecurityTokenHandler(); | |
var key = Encoding.ASCII.GetBytes(_jwtBearerTokenSettings.SecretKey); | |
var tokenDescriptor = new SecurityTokenDescriptor | |
{ | |
Subject = new ClaimsIdentity(new Claim[] | |
{ | |
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), | |
new Claim(ClaimTypes.Name, user.UserName.ToString()), | |
new Claim(ClaimTypes.Email, user.Email) | |
}), | |
Expires = DateTime.UtcNow.AddMinutes(_jwtBearerTokenSettings.ExpiryTimeInMinutes), | |
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature), | |
Audience = _jwtBearerTokenSettings.Audience, | |
Issuer = _jwtBearerTokenSettings.Issuer | |
}; | |
var token = tokenHandler.CreateToken(tokenDescriptor); | |
return tokenHandler.WriteToken(token); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment