NestJS User Authentication with LoginRadius API

Want to authenticate users on your NestJS app? Follow this tutorial to learn how to authenticate users using a password and perform authorization using access tokens.
profile
Mary Gathoni2022-03-23
guest-post,nestjs-authentication-with-loginradius-api
Table of Contents

Authentication vs. Authorization

To create secure applications, you need a way to authenticate and authorize your users. In this tutorial, you will learn to authenticate users in your NestJS apps using LoginRadius Authentication API.

Authentication vs. Authorization

Authentication and authorization are often seen as similar concepts, but they are not. Authentication is the process of verifying that a user is who they claim to be, while authorization is verifying which resources the user has access to.

Authentication always comes first before authorization since you first need to identify the user before determining what level of access to give them.

You can either choose to implement your own authentication strategy or leverage the benefits of a third-party identity platform. A do-it-yourself solution is prone to security errors, takes up a lot of time, and can increase the complexity of your application.

With a third-party solution, you get access to multiple authentication methods, advanced security features, and you write less code.

User Authentication with LoginRadius

LoginRadius is a no-code identity platform offering authentication, authorization, account security, and privacy solutions.

The Authentication API provided by LoginRadius allows you to authenticate a user using an email and a password. Once the user is verified, LoginRadius responds with an access token. The user will, in turn, use the access token to send requests to protected endpoints.

User Authentication in NestJS

NestJS is a Node.js framework built on Express.js with an Angular-like architectural structure. It is used to build scalable and modern server-side applications. The following sections will guide you in creating a simple NestJS application with authentication.

Set Up the Project

Create a new NestJS project by running the following commands

Set Up LoginRadius

To authenticate a user using LoginRadius in NestJS, you need credentials: an API key and an API secret.

Get your account credentials by creating a free LoginRadius account and head over to the dashboard.

Create an app and select configuration and then get your app's credentials from the API credentials panel.

Set Up .env file

Since the API key and API secret from the LoginRadius dashboard are sensitive, you will store them in the file.

You will need the dotenv module to access the your environment variables. Run the following command to install it.

Add the API key, API secret, and Secure One Time Token(SOTT) to the.env file.

Authentication Flow

In this project, you will be authenticating the user using their email and password. The following are the major steps you will be following:

  • Create a signup route that will get the user information and create a new user.
  • Create a login route that accepts the email and password of the user. This data will be authenticated, and an access token will be sent back in the response.
  • Create a protected route that will only accept requests with valid access tokens.

Create an Authentication Module

Generate an auth module, controller, and service by running the following code.

Create a User

To create a user, you need to create a signup route that will accept the email and password.

Since you are using TypeScript, define the DTO (Data Transfer Object) schema to validate the user data passed in the request body.

In the folder, add the folder and create a class in the file.

Next, inside the , import the DTO to be used to validate the request body.

Generate Auth Service File

A service file is used to abstract the business logic away from the controller. You will be handling the actual authentication and authorization process in this file.

Generate a service for auth by running the following command.

Next, populate the auth.service file by adding the signup method.

Note that you are also importing the user DTO and the loginradius-sdk at the top of the file. To execute the signup method in the signup route, inject it in the file.

Before registering the user, validate if the email is already in use. First, install using the following command.

Next import and configure it and since you will be using variables from the file, remember to also configure .

Next, check if the email is already in use.

If the email is not already in use, register the user.

In the above code, you register a new user by passing in the user data to the authentication API. The object defines how the email and password will be stored in the database.

Log In the User

To log in the user, pass in the email and password to the authentication API of LoginRadius.

In , add the login function.

Since you are expecting the same type of data from the request body, i.e., the email and password, like in the signup route, you can reuse the user DTO.

Next, add the login functionality.

In the above code, you are logging in the user through loginradius-sdk. If successful, send back the in the response body. The user will use the access token to access protected routes.

Inject the login method in the file to use it in the login route.

Access Protected Routes

For protected routes, like accessing a user dashboard, the user will need to send the access token with the request. The access token will then be verified, and if valid, the application will be granted access.

The user will need to store the . In this tutorial, you will be storing the token in the authorization header as a bearer token. Another alternative would be to use HTTP-only cookies.

In NestJS, guards are responsible for handling authorization. They determine whether a request will be handled by the route.

In , add the following code.

In the above code, you define the auth guard that will be used to decorate the protected routes. The token is extracted from the request authorization header and passed to the method defined in . This method will be responsible for verifying the token.

In , create the method. This method will send the access token to LoginRadius for verification.

Now, create a protected route. In , add the following.

Now, every route you add to will require a valid access token.

Test with Postman

Use Postman or any other REST client of your choice to test the routes you have created.

First, create a test user by sending a POST request to the signup endpoint. Remember to include the email and password of the user in the request body.

You should receive a "Sign up successful" message if the request is successful.

Create a user

Next, log in the user by sending the login credentials to the login endpoint of your application.

If successful, you should receive the access token.

Sign up a user

Finally, use the access token to access the protected route. Add the token to the authorization header.

Sign up a user

Conclusion

In this tutorial, you have learned how to implement NestJS authentication using the LoginRadius Authentication API. You have seen how to log in a user and use an access token to protect specific routes.

You can find the source code used in this tutorial on Github.

Learn more about the LoginRadius Authentication API from the documentation files. It has more identity management features than discussed in this tutorial. You can use these features to further enhance authentication as you need in your NestJS projects.

Mary Gathoni
By Mary GathoniShe is a software developer with a passion for technical writing. She strives to create content that is educative and easily understandable. In her free time, she enjoys being outdoors with friends.
Featured Posts

How to Implement JWT Authentication for CRUD APIs in Deno

Multi-Factor Authentication (MFA) with Redis Cache and OTP

Introduction to SolidJS

Build a Modern Login/Signup Form with Tailwind CSS and React

Implement HTTP Streaming with Node.js and Fetch API

NestJS: How to Implement Session-Based User Authentication

NestJS User Authentication with LoginRadius API

How to Authenticate Svelte Apps

Flutter Authentication: Implementing User Signup and Login

How to Secure Your LoopBack REST API with JWT Authentication

Node.js User Authentication Guide

Your Ultimate Guide to Next.js Authentication

Local Storage vs. Session Storage vs. Cookies

How to Secure a PHP API Using JWT

Using JWT Flask JWT Authentication- A Quick Guide

Build Your First Smart Contract with Ethereum & Solidity

What are JWT, JWS, JWE, JWK, and JWA?

How to Build an OpenCV Web App with Streamlit

32 React Best Practices That Every Programmer Should Follow

How to Build a Progressive Web App (PWA) with React

Bootstrap 4 vs. Bootstrap 5: What is the Difference?

JWT Authentication — Best Practices and When to Use

What Are Refresh Tokens? When & How to Use Them

How to Upgrade Your Vim Skills

How to Implement Role-Based Authentication with React Apps

How to Authenticate Users: JWT vs. Session

How to Use Azure Key Vault With an Azure Web App in C#

How to Implement Registration and Authentication in Django?

11 Tips for Managing Remote Software Engineering Teams

Implementing User Authentication in a Python Application

Add Authentication to Play Framework With OIDC and LoginRadius

Share On:
Share on TwitterShare on LinkedIn