|
|
|
|
using Microsoft.Extensions.Caching.Memory;
|
|
|
|
|
using Microsoft.Extensions.Configuration;
|
|
|
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
|
|
|
using System.Reflection;
|
|
|
|
|
using System.Security.Claims;
|
|
|
|
|
using System.Text;
|
|
|
|
|
|
|
|
|
|
namespace Common.Helper.Auth
|
|
|
|
|
{
|
|
|
|
|
public class AuthHelper
|
|
|
|
|
{
|
|
|
|
|
|
|
|
|
|
private readonly IConfiguration _configuration;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/// <param name="configuration"></param>
|
|
|
|
|
public AuthHelper(IConfiguration configuration)
|
|
|
|
|
{
|
|
|
|
|
_configuration = configuration;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public string GetToken(dynamic userInfo)
|
|
|
|
|
{
|
|
|
|
|
var dynamicProperties =(PropertyInfo[]) userInfo.GetType().GetProperties();
|
|
|
|
|
// token中的claims用于储存自定义信息,如登录之后的用户id等
|
|
|
|
|
var claims = new Claim[dynamicProperties.Length];
|
|
|
|
|
for (var i = 0; i < dynamicProperties.Length; i++)
|
|
|
|
|
{
|
|
|
|
|
claims[i] = new Claim(dynamicProperties[i].Name, userInfo.GetType().GetProperty(dynamicProperties[i].Name).GetValue(userInfo,null)?.ToString());
|
|
|
|
|
}
|
|
|
|
|
// 获取SecurityKey
|
|
|
|
|
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("Authentication")["SecurityKey"]));
|
|
|
|
|
var token = new JwtSecurityToken(
|
|
|
|
|
issuer: _configuration.GetSection("Authentication")["IsSure"], // 发布者
|
|
|
|
|
audience: _configuration.GetSection("Authentication")["Audience"], // 接收者
|
|
|
|
|
notBefore: DateTime.Now, // token签发时间
|
|
|
|
|
expires: DateTime.Now.AddMinutes(30), // token过期时间
|
|
|
|
|
claims: claims, // 该token内存储的自定义字段信息
|
|
|
|
|
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256) // 用于签发token的秘钥算法
|
|
|
|
|
);
|
|
|
|
|
// 返回成功信息,写出token
|
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|