.NET Core JWT Auth for beginners

The_Polyglot
6 min readJul 10, 2020

Disclaimer: This article is written by a dev who is not a life long .NET guru. I do not wish to know the intricacies of the .NET platform and every detail of every abstraction that makes it tick. I just like to get the thing done and not spend all my time putting together processes that are common in every application.

Pre-requisites:

  • An understanding of JWT tokens and Bearer token authentication: This tutorials for those of you who have done it before and now have to figure it out with .Net Core. If you have not worked with JWT tokens before then this is not the tutorial for you.
  • Basic setup with .Net Core: Im not covering how database context objects are made, how controllers work, what the Setup file’s purpose is or the endless details of the framework. If you’ve got a scaffolding together and you now need to get an auth flow in place, your reading the right article

I primarily work with Node.js & PHP’s Laravel these days because of one simple factor. I love prototyping and getting my API up and running with ease.

.Net is a different beast in itself. You have two different breeds of .Netters. Those who have worked with it sense 2005 and have an appreciation for each and every piece of the puzzle. Then you have the modern developer who enjoys hopping into a different framework every other year and poking around. Us polyglots find enjoyment in picking up frameworks like flask, laravel, express, rails and running with it in 10 minutes. We enjoy seeing results and walking away with a sense of Knowledge gained and for that reason, .Net can conjure unsettling feelings.

.Net’s JWT flow is what I would consider rather complex. A comment from a long term .Net Guru explained the reason behind the complexity:

This is primarily a complaint with the JWT middleware. The runtime doesn’t handle any security itself. I will say the other platforms mentioned can make it simpler because they’re only concerned with simple, single track auth stories.

AspNet auth uses the same base abstractions for every type of auth (identity + claims). It’s not just jwt. Apps can also simultaneously have numerous types of auth (OAuth, forms, saml, ws-trust/fed, ntlm, Kerberos, etc). It will automatically analyze requests and determine which to use. All middleware is baked into this paradigm, and every permutation of those auth types.

This all exists so any auth mechanism can use the same ClaimsPrincipal and Policy abstractions for security. It’s necessary so that every security implementation supported on a given application becomes a discrete path of execution and coexists with the other auth methods any application can potentially support. The auth story has been essentially the same since Asp.net under 3.5 (2007):

If you understand that set of pipelines, auth is trivial, but it does take some work to grok

So with that lets’ dig into making a quick .Net core app that handles JWT tokens.

This is the overview of the steps we will take to create an authentication flow.

  1. Create .Net core web api
  2. Create user model
  3. Create authentication scheme to Startup.cs
  4. Create auth endpoint
  5. Create user service for fetching a user from our JWT token

Step 1.) Create .Net core web api

assuming you have installed all needed tooling, run

Step 2.) Create User Model

Next Create a user model. Ideally you’ll want to place it in a model directory. There are plenty of tutorials for connecting your model to a Database context object to easily access your database of choice. We wont cover that here as we are focusing only on authentication put a quick google search will turn up everything you need.

We’re also not going to discuss Data Annotations but all you need to understand from a high level perspective is they check the values your trying to update the user with and if they meet the requirements implied by the annotations. Just think of them as implicitly executed functions at run time.

Step 3.) Add authentication scheme to Startup.cs

There’s a lot going on in this snippet but only a few things that need payed attention to. In your ConfigureServices method. Create a key using the Encoding library. Now copy the the AddAuthentication portion along with its chained method AddJwtBearer.

These do just as they say. They add an authentication step to each request that comes through your api, using the options specified. Add JwtBearer helps our app understand what JWT Bearer token to expect and that the signed key provided needs to match the key we specified. You need to include that secret key from you app settings file but we will not get into that for the sake of simplifying this tutorial.

After that, just add app.UseAuthentication() followed by app.UseAuthorization() to your Configure method and you’r good to go on this step.

Step 4.) Create Auth Endpoint

You need a basic endpoint for users to send lets say an email and password. If they both check out then we’ll return a signed token that they can use with every to reach endpoints needing authentication.

Heres my AuthController.cs. All you need to worry about is the Authenticate method and what it’s doing.

Lets break it down as its quite a bit:

  • .Net grabs our Json provided fields from the post body and injects them into a basic object called Authenticate that looks almost identical to our User.cs object but with only an Email and Password.
  • We fetch our user matching the email and password. We’re not dealing with password encryption cause its outside the scope of the tutorial but please, encrypt your password.
  • Create a token handler. The handler will build the token for us.
  • Create a key again the same way we did before.
  • Build a token descriptor: We provide it a ClaimsIdentity object which is provided an array of Claims. If you’ve worked with JWT tokens you understand that they have claims which are representations of who issued the token, the users email, users and users password. It also needs the time till the token expires as we don’t want user’s to obtain a token that lasts forever.
  • Use the handler we made to create a token and then return a written token in a 200 response to the client.

Thats the most difficult part of the whole process. If you can wrap your head around that, the rest is a cake walk.

Step 5.) Create user service for fetching a user from our JWT token

Let’s say we hit an endpoint for fetching the active users info. Many times we see these endpoints URL referred to as ‘/me’.

In the first code snippet is a controller action handling the endpoint ‘/me’. In the Authorization header of the HTTP request, the user has the string. Bearer <token provided from auth endpoint>. Fro the changes we made in the Startup.cs file, .Net decodes this token, fetches the claims from it and stores the HttpContext.User object which is included in every controller that extends BaseController .

I wont go into the details of building a service but lets build a quick UserService and have a method that simply

  • Grabs the user’s id from _httpContextAccessor.HttpContext.User.Identity.Name (look at our auth endpoint. We assigned the user Id to the Name claim).
  • Fetch the user using this Id and return it.

And just like that, we have a service method that can fetch our user at any time needed. At first I built a middleware class for fetching the user on every request but not every function needs the active user and having an optional method reduces the amount of times that users queried for.

If you walk away from this confused as to what goes where, don’t be discouraged. I only showed the key methods and essential functionality to get a quick auth POC off the ground. Theres still much to be done for this to be production worthy. Keep this as a reference as you go about setting up your auth and hopefully some of the ways I approached can be applicable to your needs.

--

--

The_Polyglot

Live to share and teach. The numbers mean nothing if I reach 1. 8 years startups, now at 🍏