Return user roles from bearer token of Web API Return user roles from bearer token of Web API asp.net asp.net

Return user roles from bearer token of Web API


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