首页 文章

无法在MVC前端应用程序中获得持有者令牌的声明

提问于
浏览
1

我可以调用API来获取本地令牌,但是如何在我的ASP.NET MVC前端应用程序中使用此令牌并获取声明 . 我试过这样的事情(下面提到),但有些我怎么也无法解密令牌并获得索赔 . 我确保机器密钥是相同的 .

var unencryptedToken = Startup.OAuthBearerOptions.AccessTokenFormat.Unprotect(accessToken); 
//(This line is always returning the null)
var identity = unencryptedToken.Identity;
var id = new ClaimsIdentity(identity.Claims, DefaultAuthenticationTypes.ApplicationCookie);

你能帮我解决这个问题吗?

我使用下面的文章构建我的webapi来生成令牌 . http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

此致,Rupesh

1 回答

  • 0

    虽然老问题,但我今天必须实施这个 . 您可以尝试从 RequestContext's User 对象获取信息,如下所示:

    var userName = idt.Claims.Where(x => x.Type == "UserName").Select(x => x.Value).First();
    var roles = idt.Claims.Where(x => x.Type == "role").Select(x => x.Value).FirstOrDefault();
    
    return new[] {$"'userNameClaim':'{userName}','rolesClaim':'{roles}'"};
    

    我添加了 extension method 以便更容易返回逗号分隔的角色字符串:

    public static class RequestExtensions
    {
        public static string GetRoles(this HttpRequestContext context)
        {
            var idt = context.Principal.Identity as ClaimsIdentity;
            if (idt == null)
                return string.Empty;
            var roles = idt.Claims.Where(x => x.Type == "role") 
                                   .Select(x => x.Value).FirstOrDefault();
            return roles;
        }
    
        public static string GetUserName(this HttpRequestContext context)
        {
            var idt = context.Principal.Identity as ClaimsIdentity;
            if (idt == null)
                return string.Empty;
            var userName = idt.Claims.Where(x => x.Type == "UserName")
                                  .Select(x => x.Value).FirstOrDefault();
            return userName;
        }
    }
    

相关问题