Return user roles from bearer token of Web API

Sachin Trivedi picture Sachin Trivedi · Jun 7, 2014 · Viewed 17.4k times · Source

I am developing a Web API 2 project. For authentication I am using bearer token. On successful authentication the API returns a JSON object.

{"access_token":"Vn2kwVz...",
   "token_type":"bearer",
   "expires_in":1209599,
   "userName":"username",
   ".issued":"Sat, 07 Jun 2014 10:43:05 GMT",
   ".expires":"Sat, 21 Jun 2014 10:43:05 GMT"}

Now I want to return the user roles as well in this JSON object. What changes do I need to make in order to get the user roles from JSON response?

Answer

Sachin Trivedi picture Sachin Trivedi · Jun 10, 2014

After searching a lot i found that i can create some custom properties and can set them with the authentication ticket. In this way you can customize the response so that it can have the custom values which may be required at the caller end.

Here is the code to send the user roles along with the token. which was my requirement. one can modify the code to send the required data.

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        using (UserManager<ApplicationUser> userManager = _userManagerFactory())
        {
            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
                context.Options.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
                CookieAuthenticationDefaults.AuthenticationType);
            List<Claim> roles = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).ToList();
            AuthenticationProperties properties = CreateProperties(user.UserName, Newtonsoft.Json.JsonConvert.SerializeObject(roles.Select(x=>x.Value)));

            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
    }


 public static AuthenticationProperties CreateProperties(string userName, string Roles)
    {
        IDictionary<string, string> data = new Dictionary<string, string>
        {
            { "userName", userName },
            {"roles",Roles}
        };
        return new AuthenticationProperties(data);
    }

This will return me the out put as

`{"access_token":"Vn2kwVz...",
 "token_type":"bearer",
 "expires_in":1209599,
 "userName":"username",
 ".issued":"Sat, 07 Jun 2014 10:43:05 GMT",
 ".expires":"Sat, 21 Jun 2014 10:43:05 GMT"
 "roles"=["Role1","Role2"] }`

Hope this information will be helpful to some one. :)