22

我正在开发一个 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"}

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

4

2 回答 2

53

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

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

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

这将使我返回输出为

`{"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"] }`

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

于 2014-06-10T12:16:29.423 回答
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);
        }
于 2017-08-10T13:41:52.737 回答