簡體   English   中英

如何從 blazor 頁面獲取 Jwt 令牌聲明?

[英]How to get Jwt token Claim from a blazor page?

我已經構建了使用 JWT 身份驗證的應用程序。 在為客戶創建個人資料頁面時,我想獲取客戶的相關信息,例如:名字、姓氏、信用等。

我發現通過在 a.razor 頁面內使用@context.User.FindFirst("FirstName")我可以從 web 頁面上的令牌 BUT 獲取值,它以這種格式顯示FirstName:Bob ,當我只想獲取名字Bob

如何以更優雅/高效的方式從令牌中獲取值?
類似於我們將用於@context.User.Identity.Name的東西

生成聲明方法:

private List<Claim> GenerateClaims(Shared.Models.User user)
{
    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, config["Jwt:Subject"]),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
        new Claim(ClaimTypes.Name, user.userName),
        new Claim(ClaimTypes.Role, user.type),
        new Claim("FirstName", user.FirstName),
        new Claim("LastName", user.LastName),
        new Claim("Credits", user.Credits.ToString())
    };
    return claims.ToList();
}

正如你從上面的方法看到的,我想得到所有的new Claim("Example", user.Example)

你可以寫一個擴展方法:

public static class ClaimsPrincipalExtension
{
    public static string GetClaimValue(this ClaimsPrincipal claimsPrincipal, string type)
        => claimsPrincipal.FindFirst(type)?.Value ?? string.Empty;
}

用法

@context.User.GetClaimValue("FirstName")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM