post

I am currently implementing token based authentication using ASP.Net Web Api 2, Owin and Identity. The client is implemented using ExtJS framework, and the login form itself (Ext.form.Panel) is requesting additional info in order to recognize if the action was successful. The additional info is consisted of one property named “success” whose value (true/false) is used to fire a proper event handler (success or failure);

In order to accomplish this task, one must adjust his OAuthAuthorizationServerProvider implementations GrantResourceOwnerCredentials method by creating additional AuthenticationProperties.

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{

context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

using (AuthRepository _repo = new AuthRepository())
{
IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

if (user == null)
{
context.SetError("Invalid grant", "The user name or password is incorrect.");
return;
}
}

var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));

//added success parameter so that Ext.JS form can recognize action as successful
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{
"success", "true"
}
});

var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);

}

Additionally, you have to make sure that you override TokenEndPoint method to get those properties as a response when you obtain the token successfully. Without this end point the properties will not return in the response. Notice that i have removed all parameters with name that starts with dot so that “.expires” and “.issued” do not get added to the response (i do not need them).

public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
//removed .issued and .expires parameter
if (!property.Key.StartsWith("."))
context.AdditionalResponseParameters.Add(property.Key, property.Value);
}

return Task.FromResult<object>(null);
}

That’s it. Hope it helps. Happy coding!

2 thoughts on “Return additional info to the client using OAuth bearer tokens generation and Owin in WebApi

Leave a Reply

Your email address will not be published. Required fields are marked *