Asp.net web api 无法从MVC前端应用程序中的承载令牌获取索赔

Asp.net web api 无法从MVC前端应用程序中的承载令牌获取索赔,asp.net-web-api,owin,bearer-token,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 = unencry

我可以调用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来生成令牌。

问候,,
鲁佩什

虽然是一个老问题,但我今天必须实现这一点。您可以尝试从
RequestContext的
用户
对象获取信息,如下所示:

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}'"};
我添加了
扩展方法
,以便更容易返回逗号分隔的角色字符串:

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;
    }
}