Microsoft Blazor Web API with JWT Authentication
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.
If you have not heard of Blazor I encourage you to take a look at Blazor . In a nutshell it allows you to write client side and server side code using just C#, take a minute to let that sink in… This means no JavaScript needed to write UI, well… there are ways to still use JavaScript using the Javascript interop if there are no other library’s available in C#.
I hope you find this guide useful and I will post the source code onto GitHub.
Assumptions:
- 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 :)
let’s begin.
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
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);

IJwtTokenService.cs
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.

JwtTokenService.cs
The next part is easy to forget as I almost always do! We need to add the service in the Startup.cs

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.
TokenViewModel.cs
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
TokenController.cs
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.
Now I will be showing you how to implement a simple login page with Blazor and get it to send api calls to the Server we created in Part 1 and retrieve a authentication token. We will be working in the “Client” solution of the project.
Before we begin, I would like to tell you that if you are using Blazor it would be super awesome if you could use the survey link found on the index of the app when you spin it up. It will greatly help the developers inc Steve Sanderson who made this all happen, he is a true hero for C# developers. Blazor is still in an Alpha state but the more of us that report bugs and mention the amazing parts then the faster we can get this off the ground.
Let’s begin.
Open up the Client solution and you will see all the usual properties, dependencies etc.. and you will see two folders. Pages and Shared, shared are considered anything that will be used across multiple pages/areas of your app and the pages themselves and individual pages. This is not a set in stone method or naming convention but one that the team at Blazor have gone with.

Project layout
The first thing we will be doing is creating a login.cshtml page within the Pages folder. At the time of recording this tutorial, Blazor has no view template to use, so I will be adding a razor view.
Login.cshtml
Ignore all the other files in the pages folder for now, or delete them for a cleaner looking directory, though I like to keep them around while doing setup so I can see how the Blazor team do it their way.
So at the top of the page we add a “@page “/login”” this is what we use to give the URL. so ours will be “http://localhost:57778/login”. Nice and easy!

Login.cshtml
Next let’s create the form. Bootstrap comes with this template so we shall use that for ease, feel free to create your own jazzy forms if you like :) As we did in part one, just an email address and password is required for our login tutorial.
To create linked properties to the form we will create two properties, one for email and the other for password, then we will add a “bind” event to the input html tags which will link the two together in the form of two way binding.

Now let’s create an event on the submit button to make sure we have hooked it up correctly. I will show you how the C# Console.Writeline() and now write to browser consoles like javascripts console.log(); When you click on Submit it will fire the method it is attached to using the “onchange” event and write the username and password to the console. launch the web app when ready and fill the form and hit submit!

Login.cshtml

Web browser /login
As you can see we successfully show the username and password which means we have hooked it up correctly, the “WASM” is the Web Assembly which is the core of what makes Blazor run in the web browser, it is the result of the C# code getting compiled down so that a web browser is able to read the code, for more info on web assembly go to WebAssembly. The next phase is setting up our HTTP method to send the form to the Server.
Create a new property called “Token” underneath email and password. At the top of the page add “@inject HttpClient Http” This is where we will inject the standard Http client that we all know and love into our page.
We also need to move our “TokenViewModel” from the server solution to the “Shared” solution, and this is another place Blazor is amazing for, we can share models across both the UI client side and the back end server side!! and don’t forget to change the namespace. Build the application as well to make sure you have changed it in all the right places.
Project structure
We also need to add the Password property into the TokenViewModel, we are adding this in now but the password will not be needed at this stage or until Part 3 of this tutorial where we do database integration.

TokenViewModel
Next we async Task the SubmitForm method as we will be using the HTTP async methods to call the controller. We will then new up a TokenViewModel and pass in the property values. Once this is done we can fire up the app and give it a go, when you hit submit, using the Console.WriteLine() in the method we should now receive our token from the controller, wala!
Login.cshtml
I don’t know about you guys but this is sooooo much easier in Blazor than using JavaScript library’s.
At this point we can save the token to local storage for use around a more built app, this is a bit our of the scope of this tutorial as the Blazor team are still working on having a simple library to do so, but feel free to try out the JavaScript interop which can get the job done.
we will be creating a basic localDb with Entity Framework core and creating the full Authentication/Authorisation with our tokens for the full login experience. See you then! and enjoy Blazor!
Step One : IdentityDbContext setup
First step, let’s create an IdentityDbContext which is part of Entity Framework to allow us to connect to the database. We create a Data folder and then insert a new class called ApplicationDbContext, the name is up to you but generally this is what I use as it’s quite generic.

Once we have created the ApplicationDbContext we can inherit the IdentityDbContext which means we can use the ASPNet identity users. Then we add in the DbContextOptions

Now we need to hook up the Sql connection string in the appsettings.json which is located at the root lever of the Server project. We will modify or add in the connection string depending on if your file contains a template already.
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=JwtAuthenticationTutorial;Trusted_Connection=True;MultipleActiveResultSets=true"
}
Next we setup the Startup.cs file to utilise the appsettings.json and point to the connection string. Add in the EF namespace Microsoft.EntityFrameworkCore then add in the service AddDbContext as shown below.
Now we need to add the migration so we have a migration file ready to create the database. You can do this in package manager with add-migration or use dotnet core sli with dotnet ef migrations add “initial” . You will need to be in the Server project for this to work. Once you have done this you will notice a migrations folder in your Server project.

Now we need to create the database. In package manager console, use update-database and in dotnet core sli use dotnet ef database update
Boom! we have a database, this is why I love Entity framework! :) You can use SSMS or the sql server in VS to view the database if you want to take a look at it.
Step Two : Registration/Login controller methods
We can now modify the token controller to have a registration and a login method
First we create a private method to inject the UserManager
Now we create the Registration method and hook up the usermanager. As this is a simple tutorial we are not doing anything fancy, just straight up calling the user manager to create a user and because we are going to be having 2 POST methods in the controller we will be creating routes which you can see at the top of the method.

Next we need to create a login method, this will replace the GenerateToken as the method that sends back a token and the GenerateToken method will simply give the login method a token when requested.

So far so good! we now have a controller that can handle registering a user and logging in a user and sending back a generated token. You can also remove the GenerateToken method and directly call the _tokenService in the Login method, this is completely up to you, the latter would produce less code.
In this final part we will create a registration page, modify the login page and then wala! we will have a fully working JWT authentication registration and login Blazor app.
First, create a new razor view page like we did in Part 2 and copy and paste or re type out the same form. Change the @page name to “/registration” and while your at the top of the page, insert this line which will help us redirect once we login
@inject Microsoft.AspNetCore.Blazor.Services.IUriHelper UriHelper
remove the Token property and add in the redirect. For simplicity we are not handling any errors when logging in, I will leave that to you. In this we are handling what we assume will always be a success!

Go ahead and fire up the application, direct yourself to /registration and then post the form. At this point we have been redirected to the login page where we can now make a small modification to where the API points to.

And now the final bit left to do is fire up the app again and use the login form to get the token back.
Like mentioned in Part 2, we can save the local use javascript interop and then save it to localStorage, but I will leave that up to you.
Also 1 more note, if you are using JWT authentication, it is highly recommended that you use HTTPS. This can easily be achieved in Dotnet Core 2.1 thanks to the controller using it as standard but at the time of writing this I used 2.0 and hence the tutorial does not include HTTPS.
That’s it for this tutorial, hope you enjoyed it and most of all I hope that this will help you in creating your own JWT authentication apps. This was a very basic example of how a registration/login system works. JWT is super powerful and I encourage you to read further on how it can help you solve authentication to different areas of your application.
And remember to support Blazor as it is in my opinion going to be a total game changer to web development :)