【问题标题】:Return more data to the client with the bearer token using OAuth token generation WebApi使用 OAuth 令牌生成 WebApi 将更多数据返回给带有不记名令牌的客户端
【发布时间】:2021-01-06 09:39:35
【问题描述】:

有没有办法通过不记名令牌向客户端返回更多数据? 我使用 OAuthBearerAuthentication 编写了以下代码,但无法返回更多数据。我只得到“token”、“token-type”和“expires in”。

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (UserMasterRepository _repo = new UserMasterRepository())
            {
                var user = _repo.ValidateUser(context.UserName, context.Password);
                if (user == null)
                {
                    context.SetError("invalid_grant", "Provided username and password is incorrect");
                    return;
                }
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.Role, (user.role_id).ToString()));
                identity.AddClaim(new Claim(ClaimTypes.Name, user.user_name));
                identity.AddClaim(new Claim("Email", user.user_email));
                identity.AddClaim(new Claim("Phone Number", user.user_phone_no));
                context.Validated(identity);
            }
        }

我需要有关用户的更多信息。例如,我在数据库中有一个 tbl_user 字段。除了“access_token”、“token_type”和“expires_in”之外,我是否可以包含有关要返回的用户的其他信息?如果没有,如何根据access_token获取API中的用户?

任何帮助将不胜感激!

【问题讨论】:

  • 您可以使用声明返回有关用户的更多信息(例如您显示的示例代码)。使用来自tbl_user 数据表的数据再添加一项声明。但是我不认为令牌是存储所有用户信息的好地方。

标签: c# asp.net postman webapi


【解决方案1】:

我只是创建一个字典并保存用户名和用户 ID。

 if (user == null)
                    {
                        context.SetError("invalid_grant", "Provided username and password is incorrect");
                        return;
                    }                
    
                    var props =  new AuthenticationProperties(
                    new Dictionary<string, string>
                    {
                        { "user_id", user.user_id.ToString() },
                        { "user_name", user.user_name.ToString() }                    
                    });

【讨论】:

    猜你喜欢
    • 2017-10-06
    • 2019-10-07
    • 2016-09-17
    • 2021-05-18
    • 1970-01-01
    • 2021-03-12
    • 2014-10-08
    • 1970-01-01
    • 2019-10-17
    相关资源
    最近更新 更多