Created
April 4, 2021 04:48
-
-
Save FacileTechnolab/414b81f4f8acdc81b816cb743951ced1 to your computer and use it in GitHub Desktop.
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
public class AccountController : Controller | |
{ | |
private readonly IConfiguration _configuration; | |
public AccountController(IConfiguration configuration) | |
{ | |
_configuration = configuration; | |
} | |
[HttpPost] | |
[Route("Login")] | |
public IActionResult Login([FromBody] LoginRequest request) | |
{ | |
var response = new Dictionary<string, string>(); | |
if (!(request.Username == "admin" && request.Password == "Admin@123")) | |
{ | |
response.Add("Error", "Invalid username or password"); | |
return BadRequest(response); | |
} | |
var roles = new string[] { "Role1", "Role2" }; | |
var token = GenerateJwtToken(request.Username, roles.ToList()); | |
return Ok(new LoginResponse() | |
{ | |
Access_Token = token, | |
UserName = request.Username | |
}); | |
} | |
private string GenerateJwtToken(string username, List<string> roles) | |
{ | |
var claims = new List<Claim> | |
{ | |
new Claim(JwtRegisteredClaimNames.Sub, username), | |
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), | |
new Claim(ClaimTypes.NameIdentifier, username) | |
}; | |
roles.ForEach(role => | |
{ | |
claims.Add(new Claim(ClaimTypes.Role, role)); | |
}); | |
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtKey"])); | |
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); | |
var expires = DateTime.Now.AddDays(Convert.ToDouble(_configuration["JwtExpireDays"])); | |
var token = new JwtSecurityToken( | |
_configuration["JwtIssuer"], | |
_configuration["JwtIssuer"], | |
claims, | |
expires: expires, | |
signingCredentials: creds | |
); | |
return new JwtSecurityTokenHandler().WriteToken(token); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment