How can I define the clientID (or other data) in a bearer / access token using OWIN

2.3k views Asked by At

I am trying to figure out how I could put the clientID (or any additional data I might need) inside a bearer/access token.

I am using OWIN OAuth to create the tokens. I can add claims to the identity ticket that will then be ecnrypted/serialized into the token and passed back to the client.

the client then calls a protected API and the API de-serializes the token and sets up an IPrinciple for the user. This identity object contains the username, and the scopes in the ClaimsIdentity.

I would like to get additional information, such as the clientID that made the request to get the token in the first place.

I can put this data inside a claim; this clearly works but its a hack.

I've done quite a bit of searching and I am not sure how, if possible, to store additional data inside the bearer/access token.

Thanks in advance!

2

There are 2 answers

5
Taiseer Joudeh On

You can store it in AuthenticationProperties object as the code below:

            var props = new AuthenticationProperties(new Dictionary<string, string>
            {
                { 
                    "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                },
                { 
                    "userName", context.UserName
                }
            });

        var ticket = new AuthenticationTicket(identity, props);

and to read it you need to unprotect the token as the code below then read the properties from the ticket. Id din't find direct way to create the token without passing the token, I know it is not the ultimate answer but it might help.

 string token = "TOKEN GOES HERE";
 Microsoft.Owin.Security.AuthenticationTicket ticket = Startup.OAuthBearerOptions.AccessTokenFormat.Unprotect(token);
0
Cobra On

If you want to use AuthenticationProperties you must override TokenEndpoint, without that properties will not be returned

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