6

私はAsp.Net CoreとASP.NET Identityを使用しています.Claimタイプを取得すると、次のようなものが得られます

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

単純な型名のみを取得する方法。例:

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

これが可能であることはわかっていますが、解決策が見つかりません。

4

6 に答える 6

15

このドキュメントに出くわしたとき、私はこの答えを探していました:

about ページでクレームを調べると、いくつかのクレームが変な長い型名を持っていることと、おそらくアプリケーションで必要とするよりも多くのクレームがあることに気付くでしょう。

ClaimTypes長いクレーム名は、一部のクレーム タイプを .NET のクラス タイプにマップしようとする Microsoft の JWT ハンドラに由来します。次のコード行を使用して、この動作をオフにすることができます ( 内Startup)。

これは、抗 CSRF 保護の構成を新しい一意のサブ クレーム タイプに調整する必要があることも意味します。

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

このコードをStartup.csクライアントに追加したところ、クレーム タイプが短縮されました。

アップデート:

の新しいバージョンでIdentityModelは、プロパティは次のように呼ばれDefaultInboundClaimTypeMapます。

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

Identity 構成をセットアップする前に、必ずこの行を実行してください。

于 2017-12-04T10:06:42.677 に答える
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 に答える
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 に答える