As part of my work with the new Thinktecture.IdentityModel and JWT, I also updated the ASP.NET Web API integration. My first drop was based on this article. But had some limitation.
The next version is easier to use and much more flexible. It come out-of-the-box with support for:
- Basic Authentication
- Simple Web Tokens
- JSON Web Tokens
- Access Keys
- SAML 1.1 & 2.0
The first version only supported the authorization header, now I am able to retrieve credentials from various locations like:
- the authorization header (scheme / credential)
- some other header
- query string parameter
- client certificate
The usage is dead simple, you first setup a configuration that describes the credentials you want to support and where to look for them – then you let my library do the hard work to turn those credentials into a claims principal. Some examples:
JSON Web Token on the authorization header with a Bearer scheme
Some access key on a query string called apikey
Basic Authentication using an ASP.NET Membership provider
config.AddBasicAuthentication((username, password) =>
After you’ve built the configuration, you can run the authentication anywhere you want, e.g. in a global/per-route message handler, a filter or even on the controller/action method itself. You simply pass in the current HttpRequestMessage:
var authN = new HttpAuthentication(config);
ClaimsPrincipal principal = authN.Authenticate(request);
The Authenticate method has a well defined behavior:
- returns an authenticated ClaimsPrincipal if a configured credential was found and successfully authenticated.
- returns an anonymous ClaimsPrincipal if no configured credential was found
- throws a SecurityTokenValidationException if a credential was found, but authentication failed.
Not sure I can make that any simpler ;)
Once I’ve run more tests, I will upload the code to github.