Token Authentication with ASP.NET Core

I’ve spent a lot of time over the last 16 months or so working with ASP.NET Web API and Microsoft.Owin’s UseOAuthAuthorizationServer middleware extending it with custom OAuthAuthorizationServerOptions, ISecureDataFormat<T>, OAuthAuthorizationServerProvider and IAuthenticationTokenProvider implementations.

This included the use of the System.IdentityModel.Tokens InMemorySymmetricSecurityKey used in the SigningCredentials constructor to be used in signing the JWT token. And when I went to port all of this to ASP.NET Core, I learned to my surprise that there is no equivalent to UseOAuthAuthorizationServer middleware and there is no InMemorySymmetricSecurityKey. Instead, you’re on your own for creating your own authentication/authorization middleware and signing a JWT is done using a SymmetricSecurityKey (a class that used to be abstract but now is not).

Here’s my first attempt:

salt = salt ?? "0a987sdf7asdg896asdf6as9df7a7sdf8asd";
var keyBytes = Encoding.UTF8.GetBytes(
    Convert.ToBase64String(Encoding.UTF8.GetBytes(SecKey + salt)));
_symmetricSecurityKey = new SymmetricSecurityKey(keyBytes);
_tokenValidationParameters = new TokenValidationParameters
{
    CryptoProviderFactory = _symmetricSecurityKey.CryptoProviderFactory,
    ValidateIssuerSigningKey = false, //true,
    IssuerSigningKey = _symmetricSecurityKey,
    ValidateIssuer = true,
    ValidIssuer = "issuername",
    ValidateAudience = true,
    ValidAudience = "all",
    ValidateLifetime = true,
    ClockSkew = TimeSpan.Zero
};
_signingCredentials = new SigningCredentials(_symmetricSecurityKey, "HS256");

A very good blog post on this topic can be found on Stormpath’s blog. I highly recommend you read that blog post. There are any number of ways to code up your “token” endpoint. I like how easy it is to write a custom authentication and authorization token endpoint using ASP.NET Core. More fun with .NET Core to follow.