A Super Simple JWT Example
Need to set up a JSON Web Token (JWT) in a project with a .NET Core 3.1 backend? Here’s a quick and dirty example of how to do it.
First, create a Web Application project.
After we have a web application project, we are already pretty close to done. .NET makes this process easy.
The next thing we need to do is configure the JWT. This is done with a little bit of code in our Startup.cs file.
Now we will write a little bit of code that generates the JWT. We will put this in a new controller called “Auth”. This code is a bit simplistic; all it does is generate a JWT that assumes a user of bob@example.com.
Next, we need to write code that uses the JWT to verify the user. We will create a test controller that will be marked with an “Authorize” attribute. That attribute will block access to the method “Index” unless we have a valid JWT.
Now it’s time to test it. For that, we will fire up Postman.
First, let’s try and access our test method. Since we don’t have a JWT yet, we should get blocked (401 Unauthorized).
With Postman, we can hit our “Auth” method, which will give us a JWT.
Now that we have an “Auth” token, we can provide it on our test call again. Copy the JWT from our call and put it into the Authorization tab in Postman.
Now when we make the call, ASP.NET will let us in since we have a valid JWT.
This example was overly simplistic. Typically we would have real usernames and passwords to go along with this, but I wanted to create a demo that was extremely simple to help people get started.
Here is the full code for this demo: https://github.com/chadmichel/JwtTokenExample