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

时间:2016-11-02 03:05:48

标签: asp.net-web-api owin bearer-token

我可以调用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 :(得分: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;
    }
}