首页 文章

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

提问于
浏览
20

我正在开发一个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响应中获取用户角色,我需要做出哪些更改?

2 回答

  • 47

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

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

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

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

  • 2

    如上所述,通过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);
            }
    

相关问题