Rupesh Kumar prasad
Rupesh Kumar prasad

Reputation: 183

Can not get claims from bearer token in MVC front end app

I am able to call the API to get the Token in my local, However how do i use this token in my ASP.NET MVC front end application and get the claims. I tried something like this (mentioned below) but some how i am not able to decrypt the token and get the claims. I made sure that Machine key’s are same.

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

Can you help me with this??

I have used below article to build my webapi to generate the token. http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

Regards, Rupesh

Upvotes: 2

Views: 1076

Answers (1)

TheVillageIdiot
TheVillageIdiot

Reputation: 40497

Though old question, but I had to implement this today. You can try getting information from the RequestContext's User object like this:

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

I have added extension method to make it easier to return comma separated string of 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;
    }
}

Upvotes: 1

Related Questions