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?
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.
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.
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. :)
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With