将更多的值添加到令牌JSON中。

3

我希望在用户登录成功后,在我的 Web 应用程序的右上角显示用户名。 我想将其与 bearer 令牌返回的 JSON 一起发送。 为了生成令牌身份验证,我正在使用 ASP.NET web API 和 Owin middlehawe。

{   
  "access_token": "blah",
  "token_type": "bearer",
  "expires_in": 599
}

我希望返回结果如下

{   
  "access_token": "blah",
  "token_type": "bearer",
  "expires_in": 599,
  "displayusername":"Hi Mundo"
}

我尝试过使用声明,但是没有得到想要的结果。

我尝试使用身份验证属性,但是不起作用。

 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
        if (validation works)
        {
           // add claims

            var moreInfo = new AuthenticationProperties(new Dictionary<string, string> { { "username", "Don"}, { "Department","MIS"} });

            var ticket = new AuthenticationTicket(identity, moreInfo);
            context.Validated(ticket);
        }
        else
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
        }
    }

我如何向owin bearer token返回的json中添加更多的值?


1
我真的不理解你的问题。在你的帖子的第一部分中,你说,“成功登录后返回用户名”,但后来又说“因为我没有授权我的用户”。这些陈述似乎相互矛盾。无论如何,声明是传递有关用户信息的最佳方式。 - Craig W.
3个回答

6

在检查有效性的同一类上覆盖TokenEndpointResponse,并按照下面的示例返回附加字段

public override Task TokenEndpointResponse(OAuthTokenEndpointResponseContext context)
{
    string thisIsTheToken = context.AccessToken;
    //add user Id and status as additional response parameter
    context.AdditionalResponseParameters.Add("displayusername", "Hi Mundo");
    context.AdditionalResponseParameters.Add("Status", "1");     
    return base.TokenEndpointResponse(context);
}

1
你可以通过向moreInfo.Dictionary添加新项来简单完成它:
moreInfo.Dictionary.Add("username", user.UserName);
moreInfo.Dictionary.Add("Department","MIS");

0
在 ApplicationOAuthProvider.cs 文件中,在以下方法中添加你的属性:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {
              
                AuthenticationProperties properties = CreateProperties(user.UserName,user.FirstName,user.LastName);
              
            }




public static AuthenticationProperties CreateProperties(string userName,string FirstName,string LastName)
        {
            IDictionary<string, string> data = new Dictionary<string, string>
            {
                { "userName", userName },
                { "FirstName", FirstName },
                { "LastName", LastName },
            };
            return new AuthenticationProperties(data);
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接