Storing Login Details Using Cookies

In this article I will be explaining about Angular cookies. So what is a cookie? Cookies are like a small package of information that is stored by the user’s browser. Cookies persist across multiple requests and browser sessions that should be set so that they can be a great method for authentication in web applications. Sometimes we will have some queries about which is to be used -- either local storage or cookies? Before that, I like to say that the cookies and local storage serve different purposes.
 
The local storage can be read on the client-side, whereas the cookies are being read on the server-side. The biggest difference is the data size is about to store, the local storage will give more space to store, whereas the cookie is limited by the size of to store.
 
As I said above the cookies are used on the server-side whereas the local storage is used on the client-side. The local storage is a way of storing the data in the client’s PC, by saving the key/ value pair in a web browser with no expiration date. We will discuss about using local storage in the next article, so coming to the point, as I said the cookies are a kind of small file that are stored on the user’s browser.
 
The cookie is a small table which will contain key and data values so,  by using this it will be very useful to carry information from one session to another session. Once we are about to store data on the server without using cookies then it will be difficult to retrieve a particular user’s information without a login on each visit to that website.
 
So far we have seen about the overview of a cookie and the usage of it. Now in this article, I will explain about storing the username and password of a static user in the cookie table. So, I have created two components, namely the login component and dashboard component, and I have set a static username and password in authservice.ts file.
 
So, when a user logs in to the login form by providing his user’s credentials the authservice checks the input and redirects the user to the dashboard if the user’s credentials are valid. If the user’s credentials are not valid it will alert by throwing enter valid email or password. And if the dashboard page is being accessed by unauthorized usage the page will be redirected to the login page automatically.
 

Setting up

 
In order to use cookies in Angular, we need to install the Angular cookie library by using the following npm package manager.
 
npm install ngx-cookie-service –save
 
After installing the package manager, we need to import the cookie service in the inside of our modules.
 
I have used the ng zorro library UI for form design, and you can find more information about ng zorro from the following link. The next step is to design a login form. So, open login.component.html file and replace the following code.
  1. <form fxFill #Login="ngForm" (ngSubmit)="onsubmit()">  
  2.     <div nz-row>  
  3.         <div nz-col nzMd="12" nzXs="24">  
  4.             <hr />  
  5.             <nz-form-item>  
  6.                 <nz-input-group>  
  7.                     <div nz-col nzMd="11" nzXs="8">  
  8.                         <nz-input-group nzPrefixIcon="user">  
  9.                             <input type="text" nz-input name="Login_name" placeholder="User Name" id="userName"  
  10.  
  11. #userName="ngModel" [(ngModel)]="Obj.username">  
  12.                             </nz-input-group>  
  13.                             <div *ngIf="Login.submitted && userName.errors" style="color: red">  
  14.                                 <div *ngIf="userName.hasError('required')">  
  15.   
  16. Login ID is required  
  17.   
  18. </div>  
  19.                             </div>  
  20.                         </div>  
  21.                     </nz-input-group>  
  22.                 </nz-form-item>  
  23.                 <nz-form-item>  
  24.                     <div nz-col nzMd="11" nzXs="8">  
  25.                         <nz-input-group nzPrefixIcon="lock">  
  26.                             <input type="password" nz-input name="user_password" placeholder="Password"  
  27.   
  28. id="password" #password="ngModel" [(ngModel)]="Obj.password">  
  29.                             </nz-input-group>  
  30.                             <div *ngIf="Login.submitted && password.errors" style="color: red">  
  31.                                 <div *ngIf="password.hasError('required')">  
  32.   
  33. Password is required  
  34.   
  35. </div>  
  36.                             </div>  
  37.                         </div>  
  38.                     </nz-form-item>  
  39.                     <div class="button">  
  40.                         <button nz-button nzType="primary">  
  41.   
  42. submit  
  43.   
  44. </button>  
  45.                     </div>  
  46.                 </div>  
  47.             </div>  
  48.         </form>  
Now open login.component.ts file and replace the following code in it.
  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. import {  
  6.     FormGroup  
  7. } from '@angular/forms';  
  8. import {  
  9.     AuthService,  
  10.     User  
  11. } from '../services/authservice.service';  
  12. import {  
  13.     Router,  
  14.     ActivatedRoute  
  15. } from '@angular/router';  
  16. import {  
  17.     CookieService  
  18. } from 'ngx-cookie-service';  
  19. @Component({  
  20.     selector: 'nz-demo-card-simple',  
  21.     templateUrl: './login.component.html'  
  22. })  
  23. export class LoginComponent implements OnInit {  
  24.     Obj: User;  
  25.     constructor(private srvLogin: AuthService, private router: Router, public activatedRoute: ActivatedRoute, private cookieService: CookieService) {  
  26.         this.Obj = new User();  
  27.     }  
  28.     ngOnInit(): void {}  
  29.     onsubmit(): void {  
  30.         this.cookieService.set('username'this.Obj.username);  
  31.         this.cookieService.set('password'this.Obj.password);  
  32.         console.log(this.cookieService.get('username'));  
  33.         console.log(this.cookieService.get('password'));  
  34.         const a = this.Obj;  
  35.         if (this.srvLogin.checkLogValues(this.Obj)) {  
  36.             this.srvLogin.isloggedin = true;  
  37.             console.log(this.srvLogin.isloggedin);  
  38.             this.router.navigate(['/dashboard']);  
  39.         }  
  40.     }  
  41. }  
The next point is to create an authentication service, we can create a service file by using the syntax.
 
ng generate service AuthService
 
The service name which I have given is Authservice and the service will be created and I have provided a default static username and password in service file so that the validation will be executed and redirected to another page (dashboard page) if the user’s credentials are being valid. Open Authservice service.ts file and replace the following code and import it in both service and as well in app-module.ts file.
  1. import {  
  2.     Injectable  
  3. } from '@angular/core';  
  4. import {  
  5.     HttpClient  
  6. } from '@angular/common/http';  
  7. import {  
  8.     CookieService  
  9. } from 'ngx-cookie-service';  
  10. @Injectable({  
  11.     providedIn: 'root'  
  12. })  
  13. export class AuthService {  
  14.     private username = 'vidya';  
  15.     private password = '123456';  
  16.     isloggedin = false;  
  17.     constructor(private http: HttpClient) {}  
  18.     checkLogValues(value: User): boolean {  
  19.         if (this.username === value.username && this.password === value.password) {  
  20.             console.log(this.username);  
  21.             console.log(this.password);  
  22.             // alert('Login valid');  
  23.             return true;  
  24.         } else {  
  25.             alert('please enter valid data');  
  26.             return false;  
  27.         }  
  28.     }  
  29. }  
  30. export class User {  
  31.     username: string;  
  32.     password: string;  
  33. }  
After that create a component named as dashboard and open dashboard.component.html file and replace the following code.
  1. <h3>Hello {{userDisplayName}} you are in Dashboard </h3>  
  2. <div style="text-align:right">  
  3.    <button nz-button nzType="danger" (click)="logout()">Logout</button>  
  4. </div>  
The next step is to open dashboard.component.ts file and replace the following code inside it.
  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. import {  
  6.     AuthService,  
  7.     User  
  8. } from '../services/authservice.service';  
  9. import {  
  10.     Router,  
  11.     ActivatedRoute  
  12. } from '@angular/router';  
  13. import {  
  14.     CookieService  
  15. } from 'ngx-cookie-service';  
  16. @Component({  
  17.     selector: 'dashboard',  
  18.     templateUrl: './dashboard.component.html'  
  19. })  
  20. export class DashboardComponent implements OnInit {  
  21.     Obj: User;  
  22.     [x: string]: any;  
  23.     userDisplayName = '';  
  24.     password = '';  
  25.     constructor(private srvLogin: AuthService, private router: Router, public activatedRoute: ActivatedRoute, private cookieService: CookieService) {  
  26.         this.Obj = new User();  
  27.         this.userDisplayName = this.cookieService.get('username');  
  28.         this.password = this.cookieService.get('password');  
  29.         this.Obj.username = this.userDisplayName;  
  30.         this.Obj.password = this.password;  
  31.         if (!srvLogin.checkLogValues(this.Obj)) {  
  32.             router.navigate(['/login']);  
  33.         }  
  34.     }  
  35.     ngOnInit(): void {}  
  36.     logout(): void {  
  37.         this.router.navigate(['/login']);  
  38.         this.cookieService.deleteAll();  
  39.     }  
  40. }  
 
 
The following next step is to log in to the dashboard by providing the user’s credentials and after the valid login, we can see the user’s name in dashboard as a welcome note by using the user’s login name. So, after entering into the dashboard page open the developer’s tool in the browser and navigate -> Application and select cookies from storage. So, on that, we can see the user name and password have been stored in the cookie table.
 
 
 
So  far we have seen about storing the user’s details in the cookie table and now we can take an overview on clearing the cookies in the cookie table; for that use deleteall() method for clearing the cookies table if  the user is about to click-> logout button.
 

Conclusion

 
In this article we have seen about using cookies in Angular for storing user’s credentials. I hope this article will be useful for you.


Similar Articles