MuriloKunze
MuriloKunze

Reputation: 15583

How to store additional data per user like session on Owin using Bearer Token

I need to store a token for thirdy party software calls on my controller after my client sign in, so I tried to save this on User Claims:

public class BaseController : ApiController
{
    private const string Token = "thirdyparty.token";
    private string Token
    {
        set
        {
            // Here I want to store a token in any way (Session, Cache, etc)
            var claimsIdentity = (ClaimsIdentity)User.Identity;
            var claims = claimsIdentity.Claims;
            var tokenClaim = claims.FirstOrDefault(x => x.Type == Token);

            if (Token != null)
            {
                claimsIdentity.RemoveClaim(tokenClaim);
            }
            claimsIdentity.AddClaim(new Claim(Token, value));
        }
        get
        {
            // Here I want to get the token
            var claimsIdentity = (ClaimsIdentity)User.Identity;
            var claims = claimsIdentity.Claims;
            var tokenClaim = claims.FirstOrDefault(x => x.Type == Token);

            return tokenClaim?.Value;
        }
    }
}

This did not work, my new Claim disappeared every time a new request is made. So, how can I store some additional information per user?

Upvotes: 0

Views: 535

Answers (1)

Marcus Höglund
Marcus Höglund

Reputation: 16811

The problem is that the claims are part of the bearer token.

So even if you add the claim to the current identity the next request will have the old claim values as they are part of the token sent with the new request.

So, if you add a claim you need to generate a new token as well and return that to the client.

One way to generate a new token is to store the OAuthAuthorizationServerOptions, used in the Startup.cs class, as a static variable and then use that where it's needed

public class Startup
{
    public static OAuthAuthorizationServerOptions OAuthServerOptions { get; private set; }
    public void Configuration(IAppBuilder app)
    {
        ConfigureOAuth(app);
        //....add the rest
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new AuthProvider() //Your derived OAuthAuthorizationServerProvider
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}

Then to generate a new token

var claimsIdentity = ... //The claim identity after you have added the new claims
    var newToken = Startup.OAuthServerOptions.AccessTokenFormat.Protect(new AuthenticationTicket(claimsIdentity, new AuthenticationProperties()));

Upvotes: 1

Related Questions