c# - 在声明中存储字符串列表 (System.Security.Claims)

标签 c# asp.net-mvc-5 wif owin claims-based-identity

我正在开发一个使用 Asp.Net 5 MVC、Owin 和 Oauth2 不记名 token 作为身份验证类型的网络应用。

我需要在 System.Security.Claims.Claim 中存储一个字符串列表 "CODEFOO,CODBAR,CODEX,.."使用自定义声明类型。

当用户请求 token 时,这个“用户代码”列表是从后端获取的,并使用特定的自定义声明类型在身份中设置。
当用户发回 token 并导航特定的 MVC 操作时,应用程序必须检查声明中的用户代码列表是否包含特定代码。

List<string> userCodes = rep.GetUserCodeFromBackEnd();
string userCodesClaimType = "http://foo.it/claim/usercodesclaimtype";

现在我正在序列化 JSON 中的字符串列表。

var claim = new Claim(userCodesCaimType, JsonConvert.SerializeObject(userCodes));

然后用这样的方式反序列化它:

var userCodesClaim = identity.Claims.FirstOrDefault<Claim>(c=>c.Type == userCodesClaimType) ;
var userCodesClaimValue = JsonConvert.DeserializeObject<List<string>>(userCodesClaim.Value);

现在的问题是: 有没有更好的方法在声明中存储值列表?
claim 有一个 ValueType文档说的属性:

The ValueType property contains a string that identifies the type information of the value. This property can be used to understand the format of the value and to provide information about how to serialize and deserialize the value. If your solution requires complex value types, it is recommended that you use standard XML schema types in the ValueType property to indicate how the Value property is meant to be serialized and deserialized from a string.

不幸的是,我没有找到任何记录该属性使用的示例。
Json 序列化好还是应该使用 ValueType 方法?

最佳答案

ValueType 是您的代码识别值如何被解释/反序列化的一种方式,例如包含 XML 模式类型。如果在来自不同来源的代码之间使用,这是有意义的,但在您自己的应用程序中,只要您知道如何解释内容,您就可以忽略它。

但是要拥有多个值,您不需要使用复杂类型。一个声明标识可以有多个具有相同 ClaimType 的声明,因此不要将代码序列化为 JSON 字符串,您应该只添加多个声明;每个用户代码一个。都具有相同的声明类型。这将使使用 HasClaim 方法检查特定用户代码是否存在成为可能。

关于c# - 在声明中存储字符串列表 (System.Security.Claims),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24849031/

相关文章:

c# - ASP.NET Web.config <runtime> 元素未继承到子应用程序中

visual-studio - 在 sitecore 多站点解决方案中管理 web.config

authentication - WIF 滑动 session 重新认证

.net - SSO 场景中的 ADFS 2.0 session 超时

wif - 替换独立的 FedUtil 以更新 system.IdentityModel

c# - LINQ to Entities 无法识别方法 'Int32

c# - ASP.NET:处理超大报告的策略

c# - 从 Server.UrlEncode 获取大写字符串

c# - 在没有自定义路由的情况下调用 Api

c# - Azure Web 应用程序。免费比基本版和标准版更快?