Friday, July 24, 2015

Reading Claims from an OAuth Bearer Token

If you are using OWIN and OAuth in your ASP.NET Web API Web Application, like me, you may not know how to read back the Claims from the Bearer Token so that you can use them in your .NET Client.

Unfortunately, this information is incredibly difficult to find!!

Fortunately, there were a few code samples scattered over the web which allowed me to piece together a suitable solution.

Below is the code needed to read back the Claims from the resultant SecurityToken:
public static JwtSecurityToken GetJwtToken(string url, string userName, string password)


        var pairs = new List<KeyValuePair<string, string>>


            new KeyValuePair<string, string>("grant_type", "password"),

            new KeyValuePair<string, string>("username", userName),

            new KeyValuePair<string, string>("password", password)



        var content = new FormUrlEncodedContent(pairs);


        using (var client = new HttpClient())


            var response = client.PostAsync(url, content).Result;

            var result = response.Content.ReadAsStringAsync().Result;


            //Deserialize the JSON into a Dictionary<string, string>

            Dictionary<string, string> tokenDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(result);

            var handler = new JwtSecurityTokenHandler();

            return handler.ReadToken(tokenDictionary["access_token"]) as JwtSecurityToken;



You will need to reference the following assemblies/NuGet packages to use this code on the client:
  1. System.IdentityModel
  2. Microsoft.Owin.Security.Jwt

Then, once you have returned the JwtSecurityToken, you simply need to write code such as the following to read back the Claims:

JwtSecurityToken token = OAuthClientWrapper.GetJwtToken(Url, userName, password);


Console.WriteLine("Claims in OAuth Bearer Access Token:");


foreach (var tokenClaim in token.Claims)


    Console.WriteLine(string.Format("{0}:{1}", tokenClaim.Type, tokenClaim.Value));


No comments:

Post a Comment