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响应中获取用户角色,需要做哪些更改?

解决方法

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

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

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

希望这个信息对一些有帮助。

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....