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

Özgür GÜL
Oct 24, 2017 · 3 min read

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

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:

Image for post
Image for post

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

Authorization: Bearer eyJhbGciOiJI…

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. :)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store