Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return user roles from bearer token of Web API

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?

like image 494
Sachin Trivedi Avatar asked Jun 07 '14 11:06

Sachin Trivedi


People also ask

How do I pass a bearer token to API?

Bearer tokens enable requests to authenticate using an access key, such as a JSON Web Token (JWT). The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value.

How do you get user role in identity?

it gives you the AspNetUserInRoles which stores UserId and RoleId. Instead you could try UserManger 's GetRoles method which will return you List<string> of roles user is assigned. But as you mentioned it will be only one role hence you can take first value from the result of GetRoles method.


2 Answers

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. :)

like image 162
Sachin Trivedi Avatar answered Oct 19 '22 04:10

Sachin Trivedi


Above changes are good to return roles as expected with one additional method in AuthorizationProvider as below: (Add this method and rock with roles...)

public override Task TokenEndpoint(OAuthTokenEndpointContext context)         {             foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)             {                 context.AdditionalResponseParameters.Add(property.Key, property.Value);             }              return Task.FromResult<object>(null);         } 
like image 43
Nirav Desai Avatar answered Oct 19 '22 04:10

Nirav Desai