从Web API的持有者令牌返回用户角色

Sac*_*edi 22 asp.net authentication asp.net-web-api2 bearer-token

我正在开发一个Web API 2项目.对于身份验证,我使用的是承载令牌.在成功验证后,API返回JSON对象.

{"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"}
Run Code Online (Sandbox Code Playgroud)

现在我想在这个JSON对象中返回用户角色.为了从JSON响应中获取用户角色,我需要做出哪些更改?

Sac*_*edi 51

搜索了很多后,我发现我可以创建一些自定义属性,并可以使用身份验证票证进行设置.通过这种方式,您可以自定义响应,以便它可以具有调用方端可能需要的自定义值.

以下是将用户角色与令牌一起发送的代码.这是我的要求.可以修改代码以发送所需的数据.

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);
    }
Run Code Online (Sandbox Code Playgroud)

这将使我退出

`{"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"] }`
Run Code Online (Sandbox Code Playgroud)

希望这些信息对某些人有所帮助.:)

  • @MarkVincze您也必须覆盖TokenEndpoint,如下所示:http://stackoverflow.com/a/24389232/224087 (5认同)

小智 5

上述更改很好地使用 AuthorizationProvider 中的一个附加方法按预期返回角色,如下所示:(添加此方法并使用角色摇滚...)

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);
        }
Run Code Online (Sandbox Code Playgroud)