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,
- Create a fresh angular project using Angular CLI.
- Integrate Bootstrap 4 so that we can easily make login forms quickly outside the box.
- Create Login component & home components and configure routes and create a simple login function that will make login requests to the database.
- 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.
- 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.
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
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.
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.
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
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.
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.
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.
Leave a Reply