Falcon.SugarApi/Falcon.SugarApi/FalconClaim/AesTokenBuilder.cs

57 lines
1.7 KiB
C#

using Falcon.SugarApi.Encryption;
using Falcon.SugarApi.JsonSerialize;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
namespace Falcon.SugarApi.FalconClaim
{
/// <summary>
/// 利用AES生成token
/// </summary>
public class AesTokenBuilder:ITokenBuilter
{
/// <summary>
/// 构造基于AES算法的token生成器
/// </summary>
/// <param name="aes">aes算法</param>
/// <param name="factory">json工厂</param>
public AesTokenBuilder(IAESEncryption aes,JsonSerializeFactory factory) {
Aes = aes;
this.Json = factory.CreateJsonSerialize();
}
public IAESEncryption Aes { get; }
public IJsonSerialize Json { get; set; }
/// <inheritdoc/>
public List<Claim>? GetClaims(string token) {
var str = this.Aes.Decrypt(FalconClaimOption.SecKey,token);
if(str.IsNullOrEmpty()) {
return new List<Claim>();
}
return this.Json.Deserialize<List<ClaimSerModel>>(str)
.Select(m => new Claim(m.Type,m.Value)).ToList();
}
/// <inheritdoc/>
public string? GetToken(List<Claim> claims) {
var obj = claims.Select(m => new ClaimSerModel(m.Type,m.Value));
return this.Aes.Encrypt(FalconClaimOption.SecKey,this.Json.Serialize(obj));
}
class ClaimSerModel
{
public ClaimSerModel(string type,string value) {
Type = type;
Value = value;
}
public string Type { get; set; }
public string Value { get; set; }
}
}
}