【问题标题】:.NET ClaimsIdentity to JWT?.NET ClaimsIdentity 到 JWT?
【发布时间】:2016-01-28 17:43:15
【问题描述】:

我正在努力确定将 .NET ClaimsIdentity 中的 Claims 列表转换为 JSON Web 令牌 (https://github.com/jwt-dotnet/jwt) 的最佳实践。如果我尝试直接在JsonWebToken.Encode() 中使用Claims 列表,则会出现循环引用异常。

我的第一个想法是将其转换为Dictionary<string,object>。挑战是将字符串Claim.Value 转换为适当的类型实例。看起来没有什么好的方法可以使用ClaimValueTypes 指示将Value 转换为适当的实例,除非有一个大而丑陋的案例声明。

想法?

【问题讨论】:

    标签: c# asp.net jwt claims-based-identity


    【解决方案1】:

    大丑案例/if 语句。我只是实现了最低限度,并将根据需要添加案例。不幸的是,ClaimValueTypes 中没有 Decimal 类型

    public static class ClaimExtensions
    {
        public static object ValueAsValueType(this Claim claim)
        {
            switch (claim.ValueType)
            {
                case ClaimValueTypes.Double:
                    return double.Parse(claim.Value);
                case ClaimValueTypes.String:
                    return claim.Value;
                default:
                    throw new Exception(string.Format("Unhandled ClaimValueType {0} in ClaimExtensions.ValueAsValueType()", claim.ValueType));
            }
        }
    
        public static List<Claim> ToClaims(this Dictionary<string, object> payload)
        {
            return payload.Select(x =>
            {
                string valueType;
                var value = x.Value;
    
                if (x.Value is double || x.Value is decimal)
                    valueType = ClaimValueTypes.Double;
                else if (x.Value is string)
                    valueType = ClaimValueTypes.String;
                else
                    throw new Exception(string.Format("Unhandled type of Claim Value {0} in ClaimExtensions.ToClaims()", value.GetType()));
    
                return new Claim(x.Key, x.Value.ToString(), valueType);
            }).ToList();
    
        } 
    }
    

    【讨论】:

    • 不过,您应该能够创建自己的 ClaimValueTypes。
    猜你喜欢
    • 2017-06-21
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    相关资源
    最近更新 更多