How to return more information on OWIN token endpoint

Using OWIN is awesome as it helps to do OAuth handshake and request hockey much easier, but there is one slight problem when you want to return a custom information from OWIN token endpoint.

Based on the specification provided hereĀ https://tools.ietf.org/html/rfc6750, the token endpoint should only have some specific fields such as:

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
    "access_token":"mF_9.B5f-4.1JqM",
    "token_type":"Bearer",
    "expires_in":3600,
    "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA"
}

However this is not what you always want, you could possibly return extra information based on your use cases, such as companyId or userTraints.

Luckily OWIN gives you an easy way to add that information just before returning the response inĀ AuthorizationServerProvider, you need to override TokenEndpoint and add you extra bits there:

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);
}

 

One last side though, you should not include too many information on the token model, the client should be able to call your resources using the access token to grab additional data.

There are also other ways to handle this by tapping into AuthenticationProperties and adding claims to it. The way to do it is very simple, Then you can create the ticket and pass the properties to it.

var properties = new AuthenticationProperties(new Dictionary<string, string>
{
    { 
        "companyId", "accountName"
    }
});

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

There you go, now once the user receives the payload it includes your companyId:

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
    "access_token":"mF_9.B5f-4.1JqM",
    "token_type":"Bearer",
    "expires_in":3600,
    "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
    "companyId": "accountName"
}

Let me know if you have any issue setting this up.

 

 

You may also like...

4 Responses

  1. vincent says:

    how do I make sure of token expiry?

  2. Amir says:

    Can you please clarify how to override AuthorizationServerProvider?

  3. pakzad says:

    @amir: when you define you’re middle-ware you usually have to define AuthorizationServerProvider

  4. pakzad says:

    @vincent: you can set it on your middle-ware where you set your signin options

Leave a Reply

Your email address will not be published.