我希望在用户成功登录后返回用户名,以显示在我的网络应用程序的右上角。我想用令牌返回的承载的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"
}
我曾尝试过声明,但那些并没有给出我想要的结果。
我曾尝试使用AuthenticationProperties但不起作用
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添加更多值?。
答案 0 :(得分:3)
在您检查有效性的同一个类上覆盖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 :(得分:0)
您可以通过将新项目添加到moreInfo.Dictionary
来简单地完成此操作:
moreInfo.Dictionary.Add("username", user.UserName);
moreInfo.Dictionary.Add("Department","MIS");
答案 2 :(得分: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);
}