Microsoft Blazor Web API with JWT Authentication — Part 1
I would like to share a guide on how to implement a JWT Authentication system into a Dotnet Core 2 Web API project that uses Microsofts new Blazor, but this same guide can be used for regular Asp.Net core 2 Web API’s.
I hope you find this guide useful and I will post the source code onto GitHub.
* You have Visual Studio (any edition) v15.7 or later. If you are using anything else then at least have knowledge of the dotnet command line.
* you know how to use the Nuget package manager
* You know C# and how to build a basic web project.
* You know what JWT tokens are and why you have chosen to use it :)
First off, follow this link Blazor getting started docs to go through the setup instructions for getting the Blazor templates and newest Dotnet Core 2 SDK.
Create a project with Blazor (Asp.NET Core hosted) and give it any name you wish. At the time of writing this guide you can only choose “No Authentication” on the template. I am using Blazor version 0.5
Next step is to install a few Nuget packages into our .Server project:
Your .Server .csproj file should look similar to this
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="2.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.Server" Version="0.5.1" />
Next we need to setup our Startup.cs file. First we need to Include the IConfiguration service so that we can use .appsettings.json file which we will look at in the next step.
Now create a “appsettings.json” file in the root of your .Server project and open it. Add in the “Jwt” json to setup the token. Basically we are adding in a private key “Key” then adding in the Issuer which is the .Server project, then we add in the Audience which will be our .Client project, the Blazor project setup means these are both the same, the expiry time is how long before the token can no longer be used. Don’t worry about the “ConnectionStrings” for now as this is for setting up a database.
Next we go back to the Startup.cs file. Now we will tell the ConfigureService to allow JwtBearer Authentication which can later use in the controllers as [Authorize]. There is quite a number of options on the TokenValidationParameters and I won’t get into all of them but they are quite self explanatory. The Configuration[“”] part is what talks to the appsettings.json file and looks for the key/value pairs
Now we are getting to the good stuff! Launch your app and using postman or just navigating through the browser, use
“ http://localhost:57778/api/SampleData/WeatherForecasts” and see how the data is showing in a GET request.
Now stop the app and go to the SampleDataController in the .Server project, Add a [Authorize] attribute to your public class SampleDataController, you will need to add the “using Microsoft.AspNetCore.Authorization” as well.
Now start the app again and repeat the process for getting the data. You should now receive a 401 Unauthorized, if you did then wahey, your controller is now secure :) alternatively you can add the [Authorize] onto the methods instead of you want to just use it on a specific method.
Next we need to create a way of building a token for the client to receive. First I will create an interface called IJwtTokenService which will have 1 method
string BuildToken(string email);
Then I am creating a new class called JwtTokenService.cs in root/Service folder of .Server project (I chose to call it service folder, call it anything you want).
First we create a new IConfiguration dependency injection in the constructor which will allow us to use the appsettings.json.
Then we create a BuildToken method to create a token which will eventually be sent back to the client.
The next part is easy to forget as I almost always do! We need to add the service in the Startup.cs
Before we start building the controller for handling clients wanting tokens, lets build a TokenViewModel so the user can send in their Email address or whatever you will want to authenticate them (usually email and password), I will keep mine simple for the purpose of this tutorial.
Next we will build the token controller or account controller depending on how you are building your app. For this I will call it TokenController and it will be an empty API controller. We will Inject the token service and create a POST method that we can use to send the client a token
Now start the app and call this controller with Postman or with your program of choice. “ http://localhost:57778/api/Token” and enter the body email and send.
You will then recieve your token
You can then copy and paste the token string into the call to http://localhost:57778/api/SampleData/WeatherForecasts and add the bearer token
When you send the request you will receive a Ok 200 response and you will receive the data from the controller, Hurrah!
Congratulations, you have successfully implemented JWT Authentication to your Asp.Net core 2 application.
This is the end of Part 1. In Part 2 I will be creating the client side for the Blazor app and show you how to use it along with a login system to compliment our new JWT API :) Im super excited about part 2!!