Asp.NET Core 2.0 WebApi JWT Authentication with Identity & MySQL
Recently I was configuring JWT authentication using Asp.NET Core 2.0 but with the latest update from 1.0 to 2.0, there was no tutorial or documentation, so I’m sharing.
In this post we will use Entity Framework Core with MySQL, and Identity with JWT. So, it will be a little long post.
If you don’t know what is JWT, check this introduction.
Source project is available at github: https://github.com/jatarga/WebApiJwt
Let’s create a new project for our WebApiJwt example project:
# mkdir WebApiJwt
# cd WebApiJwt
# dotnet new webapi
Our project will be created in a few sec.
First, we will start with connecting MySQL to our application, but before that open the project using your preferred IDE, I’ll use Rider since I’m on a Mac OS.
Create a database named webapijwt in MySQL.
Add Entity Framework Core and MySQL dependencies, our new .csproj file will look like this:
Create a directory named Entities in our project and create ApplicationDbContext.cs file in it:
This basically extends IdentityDbContext and we don’t have to create manually necessary tables in our database.
Configure our ApplicationDbContext in Startup.cs file, it will look like this:
Now, when you run the application you will see these tables are created automatically:
Now our Identity should work. Let’s configure JWT authentication
In ConfigureServices() method, add jwt stuff after adding identity, so new Startup file is:
We used Configuration[“JwtIssuer”] and Configuration[“JwtKey”] when adding JWT, so let’s add these key & values to appsettings.json:
Create a controller named AccountController for authentication that will contain /Account/Login and /Account/Register endpoints. It will produce JWT tokens using our GenerateJwtToken(…) method when login and register operation succeed:
Test our Register method using curl:
Now, it should response some thing like that:
The returned token should be stored by your client application and will send all requests with HTTP header Authorization:
Authorization: Bearer eyJhbGciOiJI…
This is up to you how you store your token. For example in Android you may save it in SharedPreferences and assign to HTTP requests or you can use localStorage with web.
Create a protected are for only signed in users using Authorize attribute:
public async Task<object> Protected()
return "Protected area";
When you do a GET request without correct token, you will get a HTTP 401 error. But if you do a correct request, it will work as expected:
In this tutorial we configured Entity Framework Core with Identity and added JWT Authentication using Asp.NET Core 2.0 Web Api. I also used dependency injection for example when creating AccountController. If you don’t know what it’s, check this tutorial by Microsoft: