CodeIn House

  • Laravel
  • WordPress
  • jQuery
  • Javascript
  • Contact
Home   Angular   Angular 10 JWT Authentication Example with Token Based Web A ...

Angular 10 JWT Authentication Example with Token Based Web API

September 19, 2020 by SNK

Angular 10 JWT Authentication Example with Token Based Web API

In this tutorial, we are going to learn, how to create Angular JWT authentication and authorization example with web API. We will go through step by step process so that you would not miss anything.

Before getting started, I would like you to know that I am going to use Laravel to develop Restful APIs which will provide me tokens for login in the frontend. You can also use others like lumen or spring boot for java. You can use any backend services supporting JWT.

I will try to make as simple and as clear as possible and divide it into smaller steps so that it would be easy to understand.

So, let’s get started,

  1. Create a fresh angular project using Angular CLI.
  2. Integrate Bootstrap 4 so that we can easily make login forms quickly outside the box.
  3. Create Login component & home components and configure routes and create a simple login function that will make login requests to the database.
  4. Since we have the angular project ready and all the necessary things, in this step, we are going to set up laravel for the token and validating users.
  5. In the last step, we are going to work with authentication and authorization in the Angular side.

1. Making Project Ready

If you do not have a node version installed, it is time to make it ready. Since I am using angular 10 it is recommended also update your project to angular 10 for recent bugs and fixes.

If you haven’t already go to your terminal and type npm update angular-cli -g. Then create a fresh project for the latest version of Angular CLI which will be version 10

You can check your node version by typing node -v in your terminal.

install_new_project_angular_10

2. Integrating Bootstrap 4 for Login Form Designs.

To integrate bootstrap 4 in angular first we have to install it via npm. Enter npm install bootstrap in your terminal and it will install the latest version of bootstrap 4 in the project.

Now, there are two ways to integrate its styles in the angular project.

The first one is adding the location of bootstrap CSS inside angular.json

angular.json
1
2
3
4
5
6
7
8
9
10
11
"assets": [
   "src/favicon.ico",
   "src/assets"
],
"styles": [
    "src/styles.css",
    "node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
    "node_modules/bootstrap/dist/js/bootstrap.min.js"
],

Next, one is just adding @import '~bootstrap/dist/css/bootstrap.min.css'; inside angular style.css

If you don’t need bootstrap.min.js in your project then, the second option is a way to go.

3. Creating Components (Login & Home Components)

Let’s get components ready. Enter ng g c Home --skipTests=true & ng g c Login --skipTests=true. It will generate two components and automatically update those in app.module.ts

Let’s also create a service that we will use later to handle login. Enter ng g s Token --skipTests=true.

If you are wondering what does skipTests=true . It will not create the test files which we never use.

Now, our file structure will look like this.

angular project file structure

If everything looks good then, let’s create forms to enter username and password to validate our login.

Inside login.component.html paste these codes to make a form ready. Here we have fields with username and function to login. You can quickly go through it.

login.component.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<div class="mt-4 col-6 offset-3">
    <div class="card">
        <div class="card-header bg-success text-white text-bold">Login to continue..</div>
        <div class="card-body">
            <form #loginForm=ngForm (submit)="loginCheck()">
                <div class="form-group row">
                    <label for="emaiInput" class="col-sm-2 col-form-label">Email</label>
                    <div class="col-sm-10">
                        <input type="email" name="email" id="email" placeholder="Enter Email" class="form-control"
                            [(ngModel)]="loginFormData.email" required>
                    </div>
                </div>
                <div class="form-group row">
                    <label for="emaiInput" class="col-sm-2 col-form-label">Password</label>
                    <div class="col-sm-10">
                        <input type="password" name="password" id="password" placeholder="Enter Password"
                            class="form-control" [(ngModel)]="loginFormData.password" required>
                    </div>
                </div>
                <div class="form-group row">
                    <div class="offset-2 col-md-12">
                        <button type="submit" class="btn btn-success" [disabled]="!loginForm.valid">Login</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

Now paste, these codes inside login.component.ts

login.component.ts
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { TokenService } from './token.service';
import { Router } from '@angular/router';
 
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
 
  public loginFormData: { email: string, password: string } = { email: null, password: null };
 
  constructor(private httpClient: HttpClient,
    private tokenService: TokenService,
    private router: Router) {
  }
 
  public loginCheck() {
    console.log('login called');
}

We don’t need to make any changes to our home component since we are using it only to redirect after login.

Configuring Routes

Go to app-routing.module.ts and inside the routes file create the routes to your specific components. In my case, I will just see the login to show my login page and '/' to load my home component. You can customize this according to your project.

app-routing.module.ts
Java
1
2
3
4
const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'login', component: LoginComponent },
];

Finally, let’s create a navbar that will have the links to login and logout. I will add it inside app.component.html but you can also create separate components for it since it will be reusable.

app.module.ts
1
2
3
4
5
6
7
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  <a class="navbar-brand">JWT Example</a>
  <ul class="navbar-nav ml-auto">
    <li class="nav-item"><a class="nav-link" routerLink="/login">Login</a></li>
    <li class="nav-item"><a class="nav-link">Logout</a></li>
  </ul>
</nav>

Make sure that the <router-outlet></router-outlet> in the component. As you have noticed we don’t have any function. It is because we will later handle it after we have configured our backend.

I tried to cover everything up on this single post. But looks like, it is really going to be very long so, I am continuing it on another post here at this link.

You can also take look at the full project in my GitHub repo.

SHARE ON
Buffer

Enjoyed this article?

Like us on

Angular angular 10 jwt authentication authentication in angular create login & logout in angular from database

Avatar for SNK

About SNK

Hello Welcome to my Blog. I develop Websites Using Laravel Framwork & WordPress. Get Latest updates on Facebook | Twitter

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Get Connected !! With Us

TOP POSTS

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

TUTORIALS TILL DATE

  • September 2022 (6)
  • June 2021 (7)
  • October 2020 (5)
  • September 2020 (6)
  • September 2018 (14)
  • August 2018 (3)
  • July 2018 (4)
  • March 2018 (8)
  • February 2018 (5)
  • January 2018 (1)
  • December 2017 (2)
  • August 2017 (8)
  • May 2017 (1)
  • April 2017 (1)
  • March 2017 (4)
  • February 2017 (3)
  • January 2017 (4)

CATEGORIES

  • Angular (2)
  • CSS3 (3)
  • D3 (3)
  • HTML5 (7)
  • JAVA (11)
  • Javascript (20)
  • jQuery (8)
  • Laravel (35)
  • Others (3)
  • PHP (11)
  • Spring (2)
  • WordPress (10)

Top Categories

  • Angular
  • CSS3
  • D3
  • HTML5
  • JAVA
  • Javascript
  • jQuery
  • Laravel
  • Others
  • PHP
  • Spring
  • WordPress

Get in Touch

DMCA.com Protection Status

Recent Articles

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

© 2012-22 CodeIn House.  •  All Rights Reserved.