ASP.NET.Tips – Consuming Bearer Tokens as a Cookie

A while ago, I talked about creating a super basic OAuth Bearer and Refresh Token System in your ASP.NET web applications: Adding a Simple Refresh Token to OAuth Bearer Tokens

Now, almost two years later, we will expand on this by creating a Cookie provider that consumes your bearer tokens to make Authorization easier. One reason to consider doing this is if you are using SignalR or any other socket service with your OAuth tokens. You can add your Bearer token in your Authorization header of your requests to SignalR, however, doing this will force your client to use LongPolling rather than actually using WebSockets as it is intended.

So, let’s create our provider:

OAuthCookieProvider.cs

 public class OAuthCookieProvider : OAuthBearerAuthenticationProvider
    {
        public override Task RequestToken(OAuthRequestTokenContext context)
        {
            if (context == null) throw new ArgumentException("context");
            var tokenCookie = context.OwinContext.Request.Cookies["BearerToken"];
            if (!string.IsNullOrEmpty(tokenCookie))
            {
                context.Token = tokenCookie;
                return Task.FromResult<object>(null);
            }
            return base.RequestToken(context);
        }
    }

And now let’s get that registered with Owin:

Startup.cs

...
public void Configuration(IAppBuilder app)
{
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
    {
        Provider = new OAuthCookieProvider()
    });
}
...

Now we can send requests with our HTTP cookie with the key of BearerToken and make it through the built in Authorize attribute without having to write anything custom.

Next, we will look at taking advantage of this CookieProvider in a .NET Signalr Client to use the full power and speed of web socket connections.

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Advertisement