Developers use Angular login session to check if the user has logged in or not! If the user hasn't logged in, then it makes sense to block the route using session management.
Now let's understand how to handle the login process with Session Authentication.
How to handle login process with Session Authentication using Angular:
We manage the login process for Session Authentication in the following steps.
- Step - 1: Create a secure login form for user credentials in Angular.
- Step - 2: Send login credentials to the backend API for validation.
- Step - 3: Receive a session token from the server upon successful authentication.
- Step - 4: Store the session token securely in the client (e.g., in cookies or local storage).
- Step - 5: Attach the session token to HTTP headers for subsequent requests.
- Step - 6: Use Angular interceptors to manage session token handling automatically.
- Step - 7: Implement session timeout and auto-logout for inactive users.
- Step - 8: Securely delete the session token on logout or session expiration.
Let's quickly understand the importance of Angular session management to get clarity on performing Angular user session.
Why Session Management in Angular?
Angular session management enables you to achieve the following:
- Prevents unauthorized access and enhances application security.
- Improves user experience with seamless session continuity.
- Reduces server load with efficient client-side session management.
- Allows session state management effectively across complex applications.
- Enables to use of tools for managing session timeout and expiration.
- Facilitates easy user authentication and authorization.
- Enables persistent user sessions across multiple tabs and windows.
Angular Login with Session Authentication
Now, let’s go through the following Angular principles for a better understanding of sessions in Angular.
Angular Routing module
Manage the user authentication permission for the Angular path.
Angular Auth Guard
This Angular function helps a lot when it comes to handling authentication. This is an interface that instructs the router whether or not to enable navigation to a specific route. We're using the 'canActivate' guard form in this case.
Angular localStorage
In an Angular program, there are three ways to store data on the client-side.
- Memory
- Session storage
- Local Storage.
Planning to hire Angular programmer for your next project?
We're using localStorage in this case, which saves data in the client browser. It can only be used in a modern browser. When the window is closed or reopened while in session storage, the data is retained; however, when the tab is closed, the data will be lost. It's easy to create a new Angular project create a new Angular project using a command. Given is the localStorage syntax which simply helps you to save up to 10MB of data in the browser.
Using the below command, create a new Angular project.
npm install bootstrap
Add the following line to the src/styles.css file after installation:
@import '~bootstrap/dist/css/bootstrap.min.css';
Build two components, one for login and one for the dashboard.
Create a service called auth.
Make a new user interface for logging in.
Using the command lines below, create a new guard called auth.
The Angular route guard, which can tell the router whether or not to enable navigation to a requested route, is referred to as Angular guard.
ng g component login
ng g component dashboard
ng g service services/auth //Build a service in the Services folder.
ng g interface interfaces/login //In the interfaces folder, build a new interface.
ng g guard guards/auth //Build a new guard in the Guards folder.
In the Login interfaces, add two properties.
Login.ts
export class ILogin { userid: string; password: string; }
Now navigate to guards/Auth.guard.ts. Import the @angular/router package's 'canActivate' interface.
Auth.guard.ts
import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate, Router } from '@angular/router'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor(private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { if (this.isLoggedIn()) { return true; } // navigate to login page as user is not authenticated this.router.navigate(['/login']); return false; } public isLoggedIn(): boolean { let status = false; if (localStorage.getItem('isLoggedIn') == "true") { status = true; } else { status = false; } return status; } }
Seeking to hire DOT NET Developers for your project?
Import the AuthGuard module into the app.module.ts format.
import { AuthGuard } from './guards/auth.guard';
Then, from the @angular/forms package, import ReactiveFormsModule and FormsModule into this file.
Our app.module.ts file should now look like this.
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { LoginComponent } from './login/login.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { AuthGuard } from './guards/auth.guard'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent, LoginComponent, DashboardComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, ReactiveFormsModule ], providers: [AuthGuard], bootstrap: [AppComponent] }) export class AppModule { }
Now edit the app-routing.modue.ts file to include login and dashboard routes. To verify user authentication, add the ‘canActivate' attribute here. It will redirect to the login page if the user is not allowed.
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { LoginComponent } from './login/login.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { AuthGuard } from './guards/auth.guard'; const routes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'dashboard', component: DashboardComponent, canActivate : [AuthGuard] }]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
In the app.component.html file, add the HTML code below.
The path of the URL is stored in routerLink, and routeLinkActive adds the class active to the selected menu. According to the route URL, will determine which View to show.
Import the ILogin interface into the auth.service.ts file.
import { ILogin } from 'src/app/interfaces/login';
Within this service class, add a Logout() method.
import { Injectable } from '@angular/core'; import { ILogin } from '../interfaces/login'; @Injectable({ providedIn: 'root' }) export class AuthService { constructor() { } logout() :void { localStorage.setItem('isLoggedIn','false'); localStorage.removeItem('token'); } }
Now import Router from the @angular/router package into the login.component.ts module. Within this file, import the login interface and the AuthService.
import { Router } from '@angular/router'; import { ILogin } from 'src/app/interfaces/login'; import { AuthService } from '../services/auth.service'
Also, import the @angular/forms package's FormBuilder, FormGroup, Validators.
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
Inside the function Object() { [native code] }, create three instances: router, service, and formBuilder.
constructor( private formBuilder : FormBuilder, private router : Router, private authService : AuthService ) { }
Set default parameters for a new variable modal as the ILogin interface.
model: ILogin = { userid: "admnin", password: "admin@123" }
Make a loginForm variable with the FormGroup sort. The message is a string, and the returnURL is also a string.
loginForm: FormGroup; message: string; returnUrl: string;
Build a new formGroup within the ngOnInit() method and apply the necessary validation to both properties.
Looking for Trusted AngularJS Development Company ? Your Search ends here.
ngOnInit() { this.loginForm = this.formBuilder.group({ userid: ['', Validators.required], password: ['', Validators.required] }); this.returnUrl = '/dashboard'; this.authService.logout(); }
Add a get method to make it easier to access the form.
get f() { return this.loginForm.controls; }
Inside this class, add the Login() method.
login() { if (this.loginForm.invalid) { return; } else { if (this.f.userid.value == this.model.userid && this.f.password.value == this.model.password) { console.log("Login successful"); //this.authService.authLogin(this.model); localStorage.setItem('isLoggedIn', "true"); localStorage.setItem('token', this.f.userid.value); this.router.navigate([this.returnUrl]); } else { this.message = "Please check your userid and password"; } } }
As a result, login.component.ts would look something like this:
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { ILogin } from 'src/app/interfaces/login'; import { AuthService } from '../services/auth.service' import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { model: ILogin = { userid: "admnin", password: "admin@123" } 6 loginForm: FormGroup; message: string; returnUrl: string; constructor( private formBuilder: FormBuilder, private router: Router, private authService: AuthService ) { } ngOnInit() { this.loginForm = this.formBuilder.group({ userid: ['', Validators.required], password: ['', Validators.required] }); this.returnUrl = '/dashboard'; this.authService.logout(); } // convenience getter for easy access to form fields get f() { return this.loginForm.controls; } login() { // stop here if form is invalid if (this.loginForm.invalid) { return; } else { if (this.f.userid.value == this.model.userid && this.f.password.value == this.model.password) { console.log("Login successful"); //this.authService.authLogin(this.model); localStorage.setItem('isLoggedIn', "true"); localStorage.setItem('token', this.f.userid.value); this.router.navigate([this.returnUrl]); } else { this.message = "Please check your userid and password"; } } } }
Login.component.html
/pre>Log In
{{message}}
Planning to hire Blockchain software developers ?
Dashboard.component.ts
Implement the logout() method inside this.ts format. This page will be inaccessible if the user is not authenticated, and the user will be directed to the login page.
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from '../services/auth.service'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.css'] }) export class DashboardComponent implements OnInit { id: string; constructor(private router: Router, private authService: AuthService) { } ngOnInit() { this.id = localStorage.getItem('token'); //console.log(this.id); } logout() { console.log('logout'); this.authService.logout(); this.router.navigate(['/login']); } }
Dashboard.component.html
The logged user's id will be shown within id if the user is registered.
Welcome, {{id}} Logout
Conclusion: Session Management in Angular
In this blog, we have learned Angular Login with Session Authentication. We can manage user authentication, route access, and the session variable using this method. If the user is not authenticated, we may use this Angular Guard method to prevent requested navigation.
Session Management in Angular Login Developers use Angular login session to check if the user has logged in or not! If the user hasn't logged in, then it makes sense to block the route using session management. Now let's understand how to handle the login process with Session Authentication. How to handle login process with Session Authentication using Angular: We manage the login process for Session Authentication in the following steps. Step - 1: Create a secure login form for user credentials in Angular. Step - 2: Send login credentials to the backend API for validation. Step - 3: Receive a session token from the server upon successful authentication. Step - 4: Store the session token securely in the client (e.g., in cookies or local storage). Step - 5: Attach the session token to HTTP headers for subsequent requests. Step - 6: Use Angular interceptors to manage session token handling automatically. Step - 7: Implement session timeout and auto-logout for inactive users. Step - 8: Securely delete the session token on logout or session expiration. Let's quickly understand the importance of Angular session management to get clarity on performing Angular user session. Why Session Management in Angular? Angular session management enables you to achieve the following: Prevents unauthorized access and enhances application security. Improves user experience with seamless session continuity. Reduces server load with efficient client-side session management. Allows session state management effectively across complex applications. Enables to use of tools for managing session timeout and expiration. Facilitates easy user authentication and authorization. Enables persistent user sessions across multiple tabs and windows. Angular Login with Session Authentication Now, let’s go through the following Angular principles for a better understanding of sessions in Angular. Angular Routing module Manage the user authentication permission for the Angular path. Angular Auth Guard This Angular function helps a lot when it comes to handling authentication. This is an interface that instructs the router whether or not to enable navigation to a specific route. We're using the 'canActivate' guard form in this case. Angular localStorage In an Angular program, there are three ways to store data on the client-side. Memory Session storage Local Storage. Planning to hire Angular programmer for your next project? Contact us We're using localStorage in this case, which saves data in the client browser. It can only be used in a modern browser. When the window is closed or reopened while in session storage, the data is retained; however, when the tab is closed, the data will be lost. It's easy to create a new Angular project create a new Angular project using a command. Given is the localStorage syntax which simply helps you to save up to 10MB of data in the browser. Using the below command, create a new Angular project. npm install bootstrap Add the following line to the src/styles.css file after installation: @import '~bootstrap/dist/css/bootstrap.min.css'; Build two components, one for login and one for the dashboard. Create a service called auth. Make a new user interface for logging in. Using the command lines below, create a new guard called auth. The Angular route guard, which can tell the router whether or not to enable navigation to a requested route, is referred to as Angular guard. ng g component login ng g component dashboard ng g service services/auth //Build a service in the Services folder. ng g interface interfaces/login //In the interfaces folder, build a new interface. ng g guard guards/auth //Build a new guard in the Guards folder. In the Login interfaces, add two properties. Login.ts export class ILogin { userid: string; password: string; } Now navigate to guards/Auth.guard.ts. Import the @angular/router package's 'canActivate' interface. Auth.guard.ts import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate, Router } from '@angular/router'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor(private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { if (this.isLoggedIn()) { return true; } // navigate to login page as user is not authenticated this.router.navigate(['/login']); return false; } public isLoggedIn(): boolean { let status = false; if (localStorage.getItem('isLoggedIn') == "true") { status = true; } else { status = false; } return status; } } Seeking to hire DOT NET Developers for your project? Contact us Import the AuthGuard module into the app.module.ts format. import { AuthGuard } from './guards/auth.guard'; Then, from the @angular/forms package, import ReactiveFormsModule and FormsModule into this file. Our app.module.ts file should now look like this. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { LoginComponent } from './login/login.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { AuthGuard } from './guards/auth.guard'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent, LoginComponent, DashboardComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, ReactiveFormsModule ], providers: [AuthGuard], bootstrap: [AppComponent] }) export class AppModule { } Read More: The Comprehensive Guide To Angular Performance Tuning Now edit the app-routing.modue.ts file to include login and dashboard routes. To verify user authentication, add the ‘canActivate' attribute here. It will redirect to the login page if the user is not allowed. import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { LoginComponent } from './login/login.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { AuthGuard } from './guards/auth.guard'; const routes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'dashboard', component: DashboardComponent, canActivate : [AuthGuard] }]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } In the app.component.html file, add the HTML code below. Toggle navigation Angular Registration Login Dashboard The path of the URL is stored in routerLink, and routeLinkActive adds the class active to the selected menu. According to the route URL, will determine which View to show. Import the ILogin interface into the auth.service.ts file. import { ILogin } from 'src/app/interfaces/login'; Within this service class, add a Logout() method. import { Injectable } from '@angular/core'; import { ILogin } from '../interfaces/login'; @Injectable({ providedIn: 'root' }) export class AuthService { constructor() { } logout() :void { localStorage.setItem('isLoggedIn','false'); localStorage.removeItem('token'); } } Now import Router from the @angular/router package into the login.component.ts module. Within this file, import the login interface and the AuthService. import { Router } from '@angular/router'; import { ILogin } from 'src/app/interfaces/login'; import { AuthService } from '../services/auth.service' Also, import the @angular/forms package's FormBuilder, FormGroup, Validators. import { FormBuilder, FormGroup, Validators } from '@angular/forms'; Inside the function Object() { [native code] }, create three instances: router, service, and formBuilder. constructor( private formBuilder : FormBuilder, private router : Router, private authService : AuthService ) { } Set default parameters for a new variable modal as the ILogin interface. model: ILogin = { userid: "admnin", password: "admin@123" } Make a loginForm variable with the FormGroup sort. The message is a string, and the returnURL is also a string. loginForm: FormGroup; message: string; returnUrl: string; Build a new formGroup within the ngOnInit() method and apply the necessary validation to both properties. Looking for Trusted AngularJS Development Company ? Your Search ends here. Contact us ngOnInit() { this.loginForm = this.formBuilder.group({ userid: ['', Validators.required], password: ['', Validators.required] }); this.returnUrl = '/dashboard'; this.authService.logout(); } Add a get method to make it easier to access the form. get f() { return this.loginForm.controls; } Inside this class, add the Login() method. login() { if (this.loginForm.invalid) { return; } else { if (this.f.userid.value == this.model.userid && this.f.password.value == this.model.password) { console.log("Login successful"); //this.authService.authLogin(this.model); localStorage.setItem('isLoggedIn', "true"); localStorage.setItem('token', this.f.userid.value); this.router.navigate([this.returnUrl]); } else { this.message = "Please check your userid and password"; } } } As a result, login.component.ts would look something like this: import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { ILogin } from 'src/app/interfaces/login'; import { AuthService } from '../services/auth.service' import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { model: ILogin = { userid: "admnin", password: "admin@123" } 6 loginForm: FormGroup; message: string; returnUrl: string; constructor( private formBuilder: FormBuilder, private router: Router, private authService: AuthService ) { } ngOnInit() { this.loginForm = this.formBuilder.group({ userid: ['', Validators.required], password: ['', Validators.required] }); this.returnUrl = '/dashboard'; this.authService.logout(); } // convenience getter for easy access to form fields get f() { return this.loginForm.controls; } login() { // stop here if form is invalid if (this.loginForm.invalid) { return; } else { if (this.f.userid.value == this.model.userid && this.f.password.value == this.model.password) { console.log("Login successful"); //this.authService.authLogin(this.model); localStorage.setItem('isLoggedIn', "true"); localStorage.setItem('token', this.f.userid.value); this.router.navigate([this.returnUrl]); } else { this.message = "Please check your userid and password"; } } } } Login.component.html Log In {{message}} Userid Userid is required Password Password is required Login /pre> Planning to hire Blockchain software developers ? Reach out us Dashboard.component.ts Implement the logout() method inside this.ts format. This page will be inaccessible if the user is not authenticated, and the user will be directed to the login page. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from '../services/auth.service'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.css'] }) export class DashboardComponent implements OnInit { id: string; constructor(private router: Router, private authService: AuthService) { } ngOnInit() { this.id = localStorage.getItem('token'); //console.log(this.id); } logout() { console.log('logout'); this.authService.logout(); this.router.navigate(['/login']); } } Dashboard.component.html The logged user's id will be shown within id if the user is registered. Welcome, {{id}} Logout Conclusion: Session Management in Angular In this blog, we have learned Angular Login with Session Authentication. We can manage user authentication, route access, and the session variable using this method. If the user is not authenticated, we may use this Angular Guard method to prevent requested navigation.
Build Your Agile Team