asp.net – 从Web API的承载令牌返回用户角色

前端之家收集整理的这篇文章主要介绍了asp.net – 从Web API的承载令牌返回用户角色前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在开发一个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响应中获取用户角色,需要做哪些更改?

@R_301_323@

搜索很多,我发现我可以创建一些自定义属性,并可以设置它们与身份验证票证。以这种方式,您可以自定义响应,以便它可以拥有呼叫者端可能需要的自定义值。

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

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...",21 Jun 2014 10:43:05 GMT"
 "roles"=["Role1","Role2"] }`

希望这个信息对一些有帮助。 原文链接:https://www.f2er.com/aspnet/252724.html

猜你在找的asp.Net相关文章