通过选项初始化类

时间:2019-07-14 20:00:25

标签: c# .net-core

我有一个用于创建用户令牌的功能,并且我有一些将根据类型安装的参数。 主要课程是ClaimsIdentity 我创建了字典,将根据键提供详细信息。但我无法使用这种方式来安装ClaimsIdentity 我有什么优雅,聪明的方法?

private string CreateUserToken(UserDTO id, EmailOrPhone emailOrPhone)
{
    Claim claims;
    var emailOrphone = new Claim("fieldName", DateTime.Now.AddHours(12).ToString("ddMMyyyy"));
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes("MySecret_Nofshonit");

    var dic = new Dictionary<EmailOrPhone, Claim>()
                {
                    {EmailOrPhone.Phone, new Claim("expiredDate", DateTime.Now.AddHours(12).ToString("ddMMyyyy")) },
                    {EmailOrPhone.Phone, new Claim("fieldName", "Phone")  },
                    {EmailOrPhone.Email, new Claim("expiredDate", DateTime.Now.AddHours(48).ToString("ddMMyyyy")) },
                    {EmailOrPhone.Email, new Claim("fieldName", "Email")  },
                };

    var tokenDescriptor = new SecurityTokenDescriptor
    {
        //Expires = DateTime.Now.AddMonths(3),
        Subject = new ClaimsIdentity(new Claim[]
        {

                        new Claim("memberId", id.ToString()),
                        new Claim("creationDate", DateTime.Now.ToString("ddMMyyyy")),
                        new Claim("expiredDate", DateTime.Now.AddMonths(3).ToString("ddMMyyyy")),
                        // ....
        }),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };

    var token = tokenHandler.CreateToken(tokenDescriptor);
    var tokenString = tokenHandler.WriteToken(token);
    var encryptedTokenString = Cryptor.Encrypt(tokenString);

    return encryptedTokenString;
}

0 个答案:

没有答案