Asp.NET Core 2.0 WebApi JWT Authentication with Identity & MySQL

Özgür GÜL
3 min readOct 24, 2017

--

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

The source project is available at github: https://github.com/ozgurrgul/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 secs.

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.

Step 1

Create a database named webapijwt in MySQL.

Step 2

Add Entity Framework Core and MySQL dependencies, our new .csproj file will look like this:

Step 3

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.

Step 4

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:

Step 5

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:

{
"JwtKey": "SOME_RANDOM_KEY_DO_NOT_SHARE",
"JwtIssuer": "http://yourdomain.com",
"JwtExpireDays": 30
}

Step 6

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:

Step 7

Lets test our Register method using curl:

Now, it should response something like that:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJtZUBvemd1ci5kayIsImp0aSI6ImMwMTgxMmQ4LTI3MjktNGJhYS04YWQwLTk1ZTI4YjgzNzc1NCIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWVpZGVudGlmaWVyIjoiZDc2MTRiNzEtN2MyOS00OTk3LTlmODUtNDNkYzlmMDI2NzZlIiwiZXhwIjoxNTExNDIwNTQ3LCJpc3MiOiJodHRwOi8veW91cmRvbWFpbi5jb20iLCJhdWQiOiJodHRwOi8veW91cmRvbWFpbi5jb20ifQ.v8YLTMTUraD7KqoHTskvcg9X_zH5WdWkcpGuHHeqYKM

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 the web.

Step 8

Create a protected are for only signed in users using Authorize attribute:

[Authorize]
[HttpGet]
public async Task<object> Protected()
{
return "Protected area";
}

When you do a GET request without a correct token, you will get an HTTP 401 error. But if you do a correct request, it will work as expected:

Conclusion

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.

Shameless plug: follow me on twitter and check my new project Landly (a landing page generator). Also, I promise I will start tweeting. :)

--

--