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.

49 lines
1.9 KiB

7 months ago
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using HybirdFrameworkCore.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
namespace Common.Util
{
public class JwtUtil
{
public static string BuildToken(string username)
{
var issuer = AppConfigurtaionServices.Configuration.GetSection("TokenOptions:Issuer").Value;
var audience = AppConfigurtaionServices.Configuration.GetSection("TokenOptions:Audience").Value;
var securityKey = AppConfigurtaionServices.Configuration.GetSection("TokenOptions:SecurityKey").Value;
var claims = new[]{
new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMonths(12)).ToUnixTimeSeconds()}"),
new Claim(ClaimTypes.Name, username)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: issuer,
audience: audience,
claims: claims,
expires: DateTime.Now.AddMonths(12),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
public static string GetUsername(HttpRequest request)
{
var authorization = request.Headers["Authorization"].ToString();
var arr = authorization.Split(" ");
JwtSecurityToken jwtToken = new JwtSecurityTokenHandler().ReadJwtToken(arr[1]);
return jwtToken.Claims.Where(m => m.Type == ClaimTypes.Name).FirstOrDefault().Value;
}
}
}