6

我正在使用 Asp.Net Core 和 ASP.NET Identity,当我得到声明类型时,我得到类似

"type":"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier",
"value":"123"

如何仅获取简单类型名称,例如:

"type":"nameidentifier",
"value":"123"

我知道这是可能的,我只是找不到解决方案。

4

6 回答 6

15

当我遇到这个文档时,我正在寻找这个答案:

当您检查 about 页面上的声明时,您会注意到两件事:一些声明具有奇怪的长类型名称,并且声明的数量超出了您的应用程序中可能需要的数量。

长声明名称来自 Microsoft 的 JWT 处理程序,该处理程序试图将某些声明类型映射到 .NET 的ClaimTypes类类型。您可以使用以下代码行(在 中)关闭此行为Startup

这也意味着您需要将反 CSRF 保护的配置调整为新的唯一子声明类型:

AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

我将此代码添加到Startup.cs我的客户,它缩短了索赔类型。

更新:

对于较新版本的IdentityModel,该属性称为DefaultInboundClaimTypeMap

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

确保在设置身份配置之前运行此行。

于 2017-12-04T10:06:42.677 回答
5

如果要获取 nameidentifier 值,代码:

User.FindFirst(ClaimTypes.NameIdentifier).Value
于 2016-03-30T19:17:12.280 回答
0

尝试这个

public static class ClaimsPrincipalExtentions
{

    private const string ShortNameProperty = "http://schemas.xmlsoap.org/ws/2005/05/identity/claimproperties/ShortTypeName";

    public static IEnumerable<Claim> GetClaimsByShortTypeName(this ClaimsPrincipal cp, string name)
    {
        return cp.Claims.Where(x => x.GetShortTypeName() == name);
    }

    public static string GetShortTypeName(this Claim claim)
    {
        string shortName;
        return claim.Properties.TryGetValue(ShortNameProperty, out shortName) ? shortName : claim.Type;
    }

}
于 2016-06-14T12:03:26.567 回答
0

我想使用短名称进行日志记录,所以我使用了这个:

var name = JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.FirstOrDefault(x => x.Value == myclaim.Type).Key ?? c.Type;

它可能不完全是 JWT 中最初发送的内容(例如,“sub”可能变成“nameid”),但它确实提供了比“http://schemas.xmlsoap.org/ws/2005/05/”更具可读性的内容身份/声明/名称标识符”。

于 2021-05-12T23:32:55.373 回答
0
using System.IdentityModel.Tokens.Jwt;

var claim = new Claim(ClaimTypes.NameIdentifier, "1");
if (JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.TryGetValue(claim.Type, out string type))
{
    var shotrClame = new Claim(type, claim.Value, claim.ValueType, claim.Issuer, claim.OriginalIssuer, claim.Subject);
}

var claim = new Claim("nameid", "1");
if (JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.TryGetValue(claim.Type, out string type))
{
    var longClameType = new Claim(type, claim.Value, claim.ValueType, claim.Issuer, claim.OriginalIssuer, claim.Subject);
}

来源:https ://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/blob/d2361e5dcd1abbf6d0ea441cdb2e7404166b122c/src/System.IdentityModel.Tokens.Jwt/ClaimTypeMapping.cs#L61

于 2021-01-04T01:43:19.917 回答
-2

System.IO.Path.GetFileName(claim.Type)

于 2016-04-26T14:03:41.267 回答