You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

116 lines
3.7 KiB
C#

3 years ago
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.IdentityModel.Tokens.Jwt;
3 years ago
using Common.Entity;
using Common.Tools;
namespace Common.Authentication
3 years ago
{
/// <summary>
/// Jwt Token提供类
/// </summary>
public class TokenProvider
{
private JwtTokenProviderOptions _jwtoptions;
3 years ago
private WebConfig _webconfig = sysOptionConfig.Webconfig;
3 years ago
public TokenProvider()
{
_jwtoptions = new JwtTokenProviderOptions
{
Audience = _webconfig.jwt_Audience,
Issuer = _webconfig.jwt_Issuer,
Secretkey = _webconfig.jwt_Secretkey,
Expiration = TimeSpan.FromMinutes(_webconfig.jwt_Expiration)
,
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_webconfig.jwt_Secretkey)), SecurityAlgorithms.HmacSha256)
};
}
/// <summary>
/// Jwt配置选项
/// </summary>
public JwtTokenProviderOptions Jwtoptions {get{ return _jwtoptions; } set{ _jwtoptions = value; } }
/// <summary>
///根据数据创建令牌
/// </summary>
/// <param name="TokenName">TokenName </param>
/// <param name="ClaimList">ClaimList</param>
/// <param name="data">data</param>
/// <param name="isEncrypt">isEncrypt</param>
/// <returns></returns>
public async Task<JwtTokenEntity> CreateToken(string TokenName, List<Claim> ClaimList, object data = null, bool isEncrypt = false)
{
try
{
var identity = await GetIdentity(TokenName);
if (identity == null)
{
return null;
}
//创建令牌
//声明令牌
var now = DateTime.Now;
var claims = ClaimList;
var jwt = new JwtSecurityToken(
issuer: _jwtoptions.Issuer
, audience: _jwtoptions.Audience
,claims: claims
, notBefore: now
, expires: now.Add(_jwtoptions.Expiration)
, signingCredentials: _jwtoptions.SigningCredentials
);
//生成令牌
var enclderjwt = new JwtSecurityTokenHandler().WriteToken(jwt);
var response = new JwtTokenEntity
{
Status = true
,
code = 200
,
message = "token授权成功"
,
Token = enclderjwt
,
Data = data
,
expires_in = (int)_jwtoptions.Expiration.TotalMinutes
};
return response;
}
catch (Exception ex)
{
var messsage = ex.Message;
return new JwtTokenEntity { code = (int)HttpCodeEnum.Error, message =ex.Message, Status = false };
}
}
/// <summary>
/// 查询令牌是否存在
/// </summary>
/// <param name="TokenKeyName"></param>
/// <returns></returns>
public Task<ClaimsIdentity> GetIdentity(string TokenKeyName)
{
return Task.FromResult(new ClaimsIdentity(new System.Security.Principal.GenericIdentity(TokenKeyName, "token"),
new Claim[] {
new Claim(ClaimTypes.Name,TokenKeyName)
}));
}
}
}