1、Nuget安装包
2、准备一个信息实体
/// <summary>
/// 信息实体
/// </summary>
class JwtEntity
{
/// <summary>
/// id
/// </summary>
public string Id { get; set; } = string.Empty;
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// 值
/// </summary>
public string Value { get; set; } = string.Empty;
}
3、获取加密后的串
private const string secretKey = "sfdkjskdlfnnierljewlkssjsffd";
/// <summary>
/// 获取字符串
/// </summary>
/// <returns></returns>
public IActionResult GetJwtString()
{
JwtEntity jwtEntity = new JwtEntity()
{
Id = "3",
Name = "TestName",
Value = "TestValue"
};
byte[] key = Encoding.UTF8.GetBytes(secretKey);
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//加密方式
IJsonSerializer serializer = new JsonNetSerializer();//序列化
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//base64加解密
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
string token = encoder.Encode(jwtEntity, key);//生成令牌
return Ok(token);
}
4、解密字符串的注解
/// <summary>
/// 鉴权注解
/// </summary>
class JwtAuthorityAttribute : Attribute, IAuthorizationFilter
{
private const string secretKey = "sfdkjskdlfnnierljewlkssjsffd";
public void OnAuthorization(AuthorizationFilterContext context)
{
var httpcontext = context.HttpContext;
var authHeader = from t in httpcontext.Request.Headers where t.Key == "Authorization" select t.Value.FirstOrDefault();
string token = authHeader.FirstOrDefault<string>() ?? string.Empty;
byte[] key = Encoding.UTF8.GetBytes(secretKey);
IJsonSerializer serializer = new JsonNetSerializer();//序列化
IDateTimeProvider provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider);
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//base64加解密
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//加密方式
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
//解密
JwtEntity jwtEntity = decoder.DecodeToObject<JwtEntity>(token, key, verify: true);
if (jwtEntity != null)
{
//通过
}
else
{
//不通过
context.Result = new EmptyResult();
}
}
5、将注解放到需要鉴权的方法或者类上,访问此方法将会进入鉴权逻辑