Creating a user authentication API in Express
Handling authentication through username and password is the most common way of securing a back-end API. This requires a front-end form to input and submit user credentials and a back-end API to validate and authorize a user session. Let's explore how to implement the back-end part of this relationship first, in Express.
Getting ready
We will continue to use Postman or another API client other than our web browser for this recipe. If you haven't set up an API client from our previous recipes, you will need one that can POST
a JSON body with a content-type of application/json
to our API. Any other content-type header will result in a 415 unsupported media
response.
How to do it...
Let's create a /api/login
route to authenticate a user using a username and password:
- First, we will need to create a new
/routes/api/login.js
route configuration to manage our API authentication. This route configuration will be similar to our/routes/api/posts.js
route...