73 lines
2.1 KiB
C#
73 lines
2.1 KiB
C#
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using OnlyPrompt.Backend.Database.Models;
|
|
using OnlyPrompt.Backend.Utils;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Linq;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace OnlyPrompt.Backend.Services.Jwt
|
|
{
|
|
public class JwtTokenService : ITokenService
|
|
{
|
|
private string _key;
|
|
private string _issuer;
|
|
private string _audience;
|
|
private TimeSpan _valid;
|
|
|
|
public JwtTokenService(IConfiguration config)
|
|
{
|
|
config = config.GetSection("Jwt");
|
|
_key = config["Key"];
|
|
_issuer = config["Issuer"];
|
|
_audience = config["Audience"];
|
|
_valid = config.GetValue<TimeSpan>("Valid");
|
|
}
|
|
|
|
public string BuildToken(UserModel user, out DateTime validUntil)
|
|
{
|
|
var claims = user.GetClaims().ToList();
|
|
validUntil = DateTime.UtcNow.Add(_valid);
|
|
claims.Add(new Claim("exp", new DateTimeOffset(validUntil).ToUnixTimeSeconds().ToString()));
|
|
claims.Add(new Claim("amr", "pwd"));
|
|
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_key));
|
|
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
|
|
var tokenDescriptor = new JwtSecurityToken(_issuer, _audience, claims, expires: validUntil, signingCredentials: credentials);
|
|
return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
|
|
}
|
|
|
|
public bool ValidateToken(string token, out ClaimsPrincipal claims)
|
|
{
|
|
var mySecret = Encoding.UTF8.GetBytes(_key);
|
|
var mySecurityKey = new SymmetricSecurityKey(mySecret);
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
try
|
|
{
|
|
claims = tokenHandler.ValidateToken(token,
|
|
new TokenValidationParameters
|
|
{
|
|
ValidateIssuerSigningKey = true,
|
|
ValidateIssuer = true,
|
|
ValidateAudience = true,
|
|
ValidIssuer = _issuer,
|
|
ValidAudience = _audience,
|
|
IssuerSigningKey = mySecurityKey,
|
|
}, out SecurityToken validatedToken);
|
|
}
|
|
catch
|
|
{
|
|
claims = null;
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
}
|
|
|
|
}
|