82 lines
2.8 KiB
C#
82 lines
2.8 KiB
C#
using JwtAuthManager.Models;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Linq;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace JwtAuthManager
|
|
{
|
|
public class JwtTokenHandler
|
|
{
|
|
public const string JWT_SECURITY_KEY = "_ll@v3Segur1d4d!123";
|
|
private const int JWT_TOKEN_VALIDITY_MINS = 20;
|
|
|
|
private readonly List<UserAccount> _userLsist;
|
|
|
|
public JwtTokenHandler()
|
|
{
|
|
_userLsist = new List<UserAccount>
|
|
{
|
|
new UserAccount{UserName = "admin", Password = "admin123", Roles = new string [] { "MUJi4t5UCmA=", "LtMPr37abss=", } },
|
|
new UserAccount{UserName = "user1", Password = "user1", Roles = new string [] { "nuepDLYs7n8=", "adnfaIJMvtc=" } },
|
|
};
|
|
}
|
|
|
|
|
|
public AuthResponse? GenerateJwtToken(AuthRequest authRequest)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(authRequest.UserName) || string.IsNullOrWhiteSpace(authRequest.Password)) return null;
|
|
|
|
// Validation
|
|
var userAcc = _userLsist.Where(x => x.UserName == authRequest.UserName &&
|
|
x.Password == authRequest.Password).FirstOrDefault();
|
|
|
|
if (userAcc == null) return null;
|
|
|
|
var tokenExpiryTimeStamp = DateTime.UtcNow.AddDays(JWT_TOKEN_VALIDITY_MINS);
|
|
//var tokenExpiryTimeStamp = DateTime.UtcNow.AddMinutes(JWT_TOKEN_VALIDITY_MINS);
|
|
var tokenKey = Encoding.ASCII.GetBytes(JWT_SECURITY_KEY);
|
|
|
|
var claimsIdentity = new ClaimsIdentity(new List<Claim>
|
|
{
|
|
new Claim(JwtRegisteredClaimNames.Name, authRequest.UserName),
|
|
});
|
|
|
|
foreach(var role in userAcc.Roles)
|
|
{
|
|
claimsIdentity.AddClaim(new Claim("permiso", role));
|
|
}
|
|
|
|
var signingCredentials = new SigningCredentials(
|
|
new SymmetricSecurityKey(tokenKey),
|
|
SecurityAlgorithms.HmacSha256Signature);
|
|
|
|
var securityTokenDescriptor = new SecurityTokenDescriptor
|
|
{
|
|
Subject = claimsIdentity,
|
|
Expires = tokenExpiryTimeStamp,
|
|
SigningCredentials = signingCredentials
|
|
};
|
|
|
|
var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
|
|
var securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor);
|
|
var token = jwtSecurityTokenHandler.WriteToken(securityToken);
|
|
|
|
return new AuthResponse
|
|
{
|
|
UserName = userAcc.UserName,
|
|
ExpiresIn = (int)tokenExpiryTimeStamp.Subtract(DateTime.UtcNow).TotalSeconds,
|
|
JwtToken = token
|
|
};
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
}
|