【问题标题】:Return user roles from bearer token of Web API从 Web API 的不记名令牌返回用户角色
【发布时间】:2014-07-28 14:20:41
【问题描述】:

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

【问题讨论】:

    标签: asp.net authentication asp.net-web-api2 bearer-token


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 嗯,这对我还不起作用。我尝试使用额外参数创建 AuthenticationProperties 对象,但它仍然只返回 access_token、token_type 和 expires_in 值。您是否必须配置其他任何东西才能使其正常工作?
    • 在我的情况下,.issued 和 .expires 值也没有设置。
    • @MarkVincze 您还必须覆盖 TokenEndpoint,如此答案:stackoverflow.com/a/24389232/224087
    • @Haider 您可以根据需要解析此角色字符串,无论您在何处使用它。或者,您可以在将 Roles 对象添加到目录时对其进行序列化。 {“角色”,角色}。我不确定,但这肯定会帮助您返回 json 对象。
    【解决方案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);
            }
    

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 1970-01-01
      • 2016-04-07
      • 2018-01-24
      • 2016-12-14
      • 2019-12-30
      • 2014-02-08
      • 1970-01-01
      • 2023-04-02
      相关资源
      最近更新 更多