问题
I want to return the user name after they logged in successfully to display on the upper right corner on my web app. I want to send it with the json that bearer the token returns. To generate the token authentication I'm using ASP.NET web API and Owin middlehawe.
{
"access_token": "blah",
"token_type": "bearer",
"expires_in": 599
}
I want the return to be like this
{
"access_token": "blah",
"token_type": "bearer",
"expires_in": 599,
"displayusername":"Hi Mundo"
}
I have tried claims but those are not giving the result I want.
I have tried to use AuthenticationProperties but doesn't work
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.");
}
}
How do I add more values to the json that the owin bearer token returns?.
回答1:
Override TokenEndpointResponse
on same class you are checking for validity and return additional field as shown in sample below
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);
}
回答2:
you can simple do it by Add new item to moreInfo.Dictionary
:
moreInfo.Dictionary.Add("username", user.UserName);
moreInfo.Dictionary.Add("Department","MIS");
回答3:
in ApplicationOAuthProvider.cs file add your properties in below method :
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);
}
来源:https://stackoverflow.com/questions/41597916/add-more-values-to-the-bearer-token-json