Return more info to the client using OAuth Bearer Tokens Generation and Owin in WebApi

You can add as many claims as you want.
You can add the standard set of claims from System.Security.Claims or create your own.
Claims will be encrypted in your token so they will only be accessed from the resource server.

If you want your client to be able to read extended properties of your token you have another option: AuthenticationProperties.

Let’s say you want to add something so that your client can have access to. That’s the way to go:

var props = new AuthenticationProperties(new Dictionary<string, string>
{
    { 
        "surname", "Smith"
    },
    { 
        "age", "20"
    },
    { 
    "gender", "Male"
    }
});

Now you can create a ticket with the properties you’ve added above:

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

That’s the result your client will fetch:

.expires: "Tue, 14 Oct 2014 20:42:52 GMT"
.issued: "Tue, 14 Oct 2014 20:12:52 GMT"
access_token: "blahblahblah"
expires_in: 1799
age: "20"
gender: "Male"
surname: "Smith"
token_type: "bearer"

On the other hand if you add claims you will be able to read them in your resource server in your API controller:

public IHttpActionResult Get()
{
    ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;

    return Ok();
}

Your ClaimsPrincipal will contain your new claim’s guid which you’ve added here:

identity.AddClaim(new Claim("guid", user.UserGuid.ToString()));

If you want to know more about owin, bearer tokens and web api there’s a really good tutorial here and this article will help you to grasp all the concepts behind Authorization Server and Resource Server.

UPDATE:

You can find a working example here. This is a Web Api + Owin self-hosted.
There’s no database involved here.
The client is a console application (there’s a html + JavaScript sample as well) which call a Web Api passing credentials.

As Taiseer suggested, you need to override TokenEndpoint:

public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
    foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
    {
        context.AdditionalResponseParameters.Add(property.Key, property.Value);
    }

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

Enable ‘Multiple Startup Projects’ from Solution -> Properties and you can run it straight away.

Leave a Comment