Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying OWIN OAuth middleware to use JWT bearer tokens

I'm currently trying to create a proof of concept for claims based authentication for a new app using a combination of the following technologies: Web API 2, OWIN middleware and JWT.

To keep things simple I started with the Web API 2 project template and changed the authentication to 'Individual User Accounts'. The sample client I created was then able to get a token by calling /Token and was able to call a sample endpoint with the OAuth bearer token. So far so good. I then added the following code to Startup.Auth.cs to try and enable JwtBearerAuthentication:

    var jwtOptions = new JwtBearerAuthenticationOptions
    {
        AllowedAudiences = audiences,
        IssuerSecurityTokenProviders = new[] { 
            new SymmetricKeyIssuerSecurityTokenProvider(issuer, signingKey) }
    };

    app.UseJwtBearerAuthentication(jwtOptions);

I expected that Web API 2 would start returning JWTs from the call to /Token, but it doesn't appear to have done anything. I've been banging my head against this for a few days with no success and the Microsoft documents aren't very forthcoming.

I also tried adding the following to my OAuthAuthorizationServerOptions

AuthorizationCodeFormat = new JwtFormat(audience, new SymmetricKeyIssuerSecurityTokenProvider(issuer, signingKey))

I could also be trying to doing the completely wrong thing.

Any ideas would be greatly appreciated.

like image 923
James O'Sullivan Avatar asked Mar 05 '14 15:03

James O'Sullivan


2 Answers

Well, now there is a setting on OAuthAuthorizationServerOptions that you can specify the format of your access token, not the authorization code, like you're doing on you example.

So, instead of:

AuthorizationCodeFormat = new JwtFormat(audience, new SymmetricKeyIssuerSecurityTokenProvider(issuer, signingKey))

You should have:

AccessTokenFormat = new JwtFormat(audience, new SymmetricKeyIssuerSecurityTokenProvider(issuer, signingKey))
like image 130
João Silva Avatar answered Oct 11 '22 03:10

João Silva


The Windows Identity Foundation uses a proprietary token format, not JWT. The JWT code you see above is for consuming tokens, not generating them. There is a helpful discussion on the ASP.NET forums.

However, in the second half of 2014 Microsoft officially released support for JWT in Windows Identity foundation, with the JSON Web Token Handler. You should be able to install and use that package to solve the problem you have described.

like image 20
sfuqua Avatar answered Oct 11 '22 05:10

sfuqua