1. 程式人生 > >Blog with ASP.NET Core and React/Redux. Part 1: Authentication

Blog with ASP.NET Core and React/Redux. Part 1: Authentication

Back-end

The goal for the back-end part is to make REST API connected to the database. This API should have two endpoints so we can log in and register.

Blog.Model

Let’s start by creating the project where all our entities(users, articles, comments) will be.

$ dotnet new classlib -o Blog.Model

The first file we create in this directory will be IEntityBase

.

With interface in place, we can create User entity.

Blog.Data

For now, this is all we need in Blog.Model project. Next project we want to create is Blog.Data.

$ dotnet new classlib -o Blog.Data

The first file we create in this directory will be IEntityBaseRepository. This interface will describe the basic methods that will be useful for work with entities.

Now let’s create a generic class that will implement the interface.

Now, when we want to create a new repository, we can inherit EntityBaseRepository and get basic functionality for the new repository.

The last class we want to add to the project is BlogContext that will inherit DBContext and will configure models and their relationships.

Blog.API

At Blog.API we will have our REST API itself. Let’s start with ViewModel user will receive after authentication. It will contain the id of the user, JWT token for authentication and it’s expiration time.

To receive this model we need auth service, that will be able to generate JWT token. Also, we put in it two methods that will hash the password and verify it.

With service in place, we can go to the Startup class and it alongside with UserRepository.

As you can see we not only inject our service but also add entity framework integration, JWT authentication, and options for JSON serializations. In Startup class, we used configuration variables for JWT authentication and database connection string. Let’s add them to appsettings.json.

And finally, it is time to create the auth controller!

In our actions, we receive ViewModels and then by using UserRepository and AuthService we authenticate/register user.

Database

The only thing left is to create a user in PostgreSQL database.

$ sudo -i -u postgres$ psql$ create user blogadmin;$ alter user blogadmin with password 'blogadmin';$ alter user blogadmin createdb;

After this, we can create and run migrations for our database.

$ cd Blog.API$ dotnet ef migrations add InitialMigration$ dotnet ef database update

Testing with Postman

Let’s run our back-end and send some request with Postman.

$ cd Blog.API$ dotnet run
register
login
trying to register with existing email