You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
2.5 KiB
69 lines
2.5 KiB
3 months ago
|
using Microsoft.IdentityModel.Tokens;
|
||
|
using System;
|
||
|
using System.Collections.Generic;
|
||
|
using System.IdentityModel.Tokens.Jwt;
|
||
|
using System.Linq;
|
||
|
using System.Security.Claims;
|
||
|
using System.Security.Cryptography;
|
||
|
using System.Text;
|
||
|
using System.Threading.Tasks;
|
||
|
using Teso_API.Models;
|
||
|
|
||
|
namespace Teso_API.Methods
|
||
|
{
|
||
|
public class TokenService : ITokenService
|
||
|
{
|
||
|
public string GenerateAccessToken(IEnumerable<Claim> claims)
|
||
|
{
|
||
|
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ServerLocation.key));
|
||
|
var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
|
||
|
|
||
|
var tokeOptions = new JwtSecurityToken(
|
||
|
issuer: ServerLocation.issuer,
|
||
|
audience: ServerLocation.issuer,
|
||
|
claims: claims,
|
||
|
expires: DateTime.UtcNow.AddDays(14),
|
||
|
signingCredentials: signinCredentials
|
||
|
);
|
||
|
|
||
|
var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
|
||
|
return tokenString;
|
||
|
}
|
||
|
|
||
|
public string GenerateRefreshToken()
|
||
|
{
|
||
|
var randomNumber = new byte[32];
|
||
|
using (var rng = RandomNumberGenerator.Create())
|
||
|
{
|
||
|
rng.GetBytes(randomNumber);
|
||
|
return Convert.ToBase64String(randomNumber);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
|
||
|
{
|
||
|
var tokenValidationParameters = new TokenValidationParameters
|
||
|
{
|
||
|
ValidateIssuer = true,
|
||
|
ValidateAudience = true,
|
||
|
ValidAudience = ServerLocation.audience,
|
||
|
ValidIssuer = ServerLocation.issuer,
|
||
|
ValidateIssuerSigningKey = true,
|
||
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ServerLocation.key)),
|
||
|
ValidateLifetime = false //here we are saying that we don't care about the token's expiration date
|
||
|
|
||
|
};
|
||
|
|
||
|
var tokenHandler = new JwtSecurityTokenHandler();
|
||
|
SecurityToken securityToken;
|
||
|
var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out securityToken);
|
||
|
var jwtSecurityToken = securityToken as JwtSecurityToken;
|
||
|
if (jwtSecurityToken == null || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
|
||
|
throw new SecurityTokenException("Invalid token");
|
||
|
|
||
|
return principal;
|
||
|
|
||
|
}
|
||
|
}
|
||
|
}
|