Angular Security - Authentication Service

  •        0
  

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.



Angular is a framework for creating single page web application. To know more about Angular and how to get started, please refer our previous article Getting started on Augular 7. Angular facilitates the security feature and protection mechanism. It provides frameworks by verifying all the routing urls with security authguard interface to validate and verify the user and its permissions.

Authentication Implementation

Singleton service class can be implemented to invoke authentication url and get the user principal to the localstorage after user key in the username and password in the login page. Injectable with provided in root will create a singleton service across angular app and isLoggedIn class level variable maintains the status of logged in of the Angular app.

File: auth.service.ts

  import { Injectable } from '@angular/core';
  import { HttpClient } from '@angular/common/http';
  import { Observable } from 'rxjs';
  @Injectable({
     providedIn: 'root'
  })
  export class AuthService {

  isLoggedIN: boolean = false;

  constructor(private httpclient: HttpClient) { }

  setIsloggedIntrue(){
     this.isLoggedIN = true
  }

  login(credentials): Observable<Object> {
  console.log(credentials);
  const formData = new FormData();
  formData.set('username', credentials.username);
  formData.set('password', credentials.password);
  return this.httpclient.post('/api/authenticate', formData);
}

 setLoggedIn() {
     this.isLoggedIN = true;
   }
}


Login component file will invoke the above login service after the user clicks the login button. Once successful login, it stores user principal data like username, userprofile image to the local storage of the browser.

File: logincomponent.ts

 login(credentials) {
    console.log(credentials);
    this.loginRepository.submitLogin(credentials)
         .subscribe((val) => {
             console.log("POST call successful value returned in body", val);
            if (val && val['id']) {
                console.log("going to navigate to equipments");
                this.authService.setLoggedIn();
                localStorage.setItem("id", val['id'])
                localStorage.setItem("username", val['firstname'])
                localStorage.setItem('userimage', val['image'])
                this.router.navigate(['home-page']); //login success, then it will land on the home page.
            } else {
                this.loginError = true
                setTimeout(() => {
                      this.loginError = false
                }, 3000)
           }
      },
      (response) => {
         console.log("POST call in error", response);
         this.loginError = true //it will show the error message saying "username or password is invalid
         setTimeout(() => {
              this.loginError = false
         }, 3000)
      },
      () => {
          console.log("The POST observable is now completed.");
   });
}

Now we need to protect all the resources urls with authenticated access. To do that, we need to implement CanActivate interface which we will check the authorization service state and local storage whether user already authenticated.

Auth guard service:

  import { AuthService } from './auth/auth.service';
  import { Injectable } from '@angular/core';
  import { CanActivate, Router } from '@angular/router'; 

  @Injectable({
     providedIn: 'root'
  })
  export class AuthGaurd implements CanActivate {

   constructor(
      private router: Router,
      private authService: AuthService) { }

      canActivate() {
         console.log(this.authService.isLoggedIN);
         if (this.authService.isLoggedIN) return true;
         if (localStorage.getItem("id")) return true;
         this.router.navigate(["/login"]);
         return false;
     }

     setLoggedIn() {
         this.authService.isLoggedIN = true;
     }
  }

Auth guard will be wired up in all the secured resources routing paths like home module by mentioning it as canActivate options. So when routing happens to that module, it will be checked whether the user logged in by invoking AuthGuard and then invoke the login page.

 import { NgModule } from "@angular/core";
 import { Routes, RouterModule } from "@angular/router";
 import { LoginComponent } from "./components/login/login.component";
 import { AuthGaurd } from './services/auth-gaurd.service';

 const approutes: Routes = [{
     path: "login",
     component: LoginComponent
 }, {
     path: "",
     loadChildren: () => import('src/app/components/home.module').then(m => m.HomeModule),
     canActivate: [AuthGaurd]
  }
];

 @NgModule({
     imports: [RouterModule.forRoot(approutes)],
     exports: [RouterModule]
  })
  export class AppRoutingModule { }

  Routersnapshot takes the current url from the route snapshot url

  this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; <!-- it fetches the current url -->

  This can be redirected once we do successful login.

  this.router.navigate([this.returnUrl]);

Http Interceptors - JWT Intereceptor/Error Interceptor:

Once user authenticated, every time the backend request should carry the authentication service bearer token so web server process the authorized request. We can create interceptor which get the token from authentication service and add it to the request headers. After header created, it can be chained to next intercept handler chain.


 @Injectable()
    export class JwtInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    <!-- add authorization header with jwt token if available -->
    let currentUser = this.authenticationService.currentUserValue;
    if (currentUser && currentUser.token) {
        request = request.clone({
        setHeaders: {
            Authorization: `Bearer ${currentUser.token}`
        }
    });
 }

   return next.handle(request);
}

Response to any request returns to 401 or 403 status code, it needs to be immedatiely redirected to the login page irrespective of the current user page. This can be handled in the interceptor response side by next.handle(request).pipe(//to check response status). It will check the status code and redirect direct to the logout.

  @Injectable()
  export class ErrorInterceptor implements HttpInterceptor {
  constructor(private authenticationService: AuthenticationService) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      return next.handle(request).pipe(catchError(err => {
      if ([401, 403].indexOf(err.status) !== -1) {
          <!-- auto logout if 401 Unauthorized or 403 Forbidden response returned from api -->
         this.authenticationService.logout();
         location.reload(true);
     }

     const error = err.error.message || err.statusText;
     return throwError(error);
  }))
 }
}


Prevent Cross Site Scripting:

Cross-site scripting (XSS) enables attackers to inject malicious code into web pages. Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation, Angular sanitizes and escapes untrusted values. Angular trusts template code, so generating templates, in particular templates containing user data, circumvents Angular's built-in protections.

Custom Domsanitizer to be implemented for sanitize by implementing the angular DOMSanitizer class. It also provides SecurityContext to indicate the type like html, style, script, urls.

  abstract class DomSanitizer implements Sanitizer {
   abstract sanitize(context: SecurityContext, value: string | SafeValue): string | null

  }

Reference:
Angular Security https://angular.io/guide/security

HTTP interceptors https://angular.io/api/common/http/HttpInterceptor

Security Context https://angular.io/api/core/SecurityContext

 


   

Nagappan is a techie-geek and a full-stack senior developer having 10+ years of experience in both front-end and back-end. He has experience on front-end web technologies like HTML, CSS, JAVASCRIPT, Angular and expert in Java and related frameworks like Spring, Struts, EJB and RESTEasy framework. He hold bachelors degree in computer science and he is very passionate in learning new technologies.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

JWT Authentication using Auth0 Library

  • java jwt authentication security

Json Web Token shortly called as JWT becomes defacto standard for authenticating REST API. In a traditional web application, once the user login credentials are validated, loggedin user object will be stored in session. Till user logs out, session will remain and user can work on the web application without any issues. Rest world is stateless, it is difficult to identify whether the user is already authenticated. One way is to use authenticate every API but that would be too expensive task as the client has to provide credentials in every API. Another approach is to use token.

Read More


RESTEasy Advanced Guide - Filters and Interceptors

  • resteasy rest-api filters interceptors java

RESTEasy is JAX-RS 2.1 compliant framework for developing rest applications. It is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol.

Read More


Introduction to Light 4J Microservices Framework

  • light4j microservice java programming framework

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Read More


Restrict Solr Admin Access

  • solr searchengine tips

Solr is a search engine built on top of Lucene. It supports REST interface and has lot of built-in capabilities. Solr package has Admin UI interface which has support to perform query and even delete the contents of the index. If you are using Solr in production then you may need to restrict access. I saw couple of questions in the group related to this topic. Thought to write an article explaining few tips to restrict the user access to Solr admin UI.

Read More


COVID19 Stats using Angular Material Design

  • angular material-design covid covid-stats

Material design is inspired from the real world building architecture language. It is an adaptable system of guidelines, components, and tools that support the best practices of user interface design. Backed by open-source code, Material streamlines collaboration between designers and developers, and helps teams quickly build beautiful products. In this article, we will build COVID stats using Angular Material design.

Read More



Getting Started on Angular 7

  • angular ui-ux front-end-framework

Angular is a platform for building responsive web, native desktop and native mobile applications. Angular client applications are built using HTML, CSS and Typescript. Typescript is a typed superset of Javascript that compiles to plain Javascript. Angular core and optional modules are built using Typescript. Code has been licensed as MIT License.

Read More


Getting Started With Django Python Web Framework

  • django python web-framework

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It is pre-loaded with user authentication, content administration, site maps, RSS feeds and many more tasks. Security features provided are cross site scripting (XSS) protection, cross site request forgery protection, SQL injection protection, click-jacking protection, host header validation, session security and so on. It also provides in built caching framework.

Read More


Push Notifications using Angular

  • angular push-notifications notifications

Notifications is a message pushed to user's device passively. Browser supports notifications and push API that allows to send message asynchronously to the user. Messages are sent with the help of service workers, it runs as background tasks to receive and relay the messages to the desktop if the application is not opened. It uses web push protocol to register the server and send message to the application. Once user opt-in for the updates, it is effective way of re-engaging users with customized content.

Read More


Angular Service Workers Usage Guide

  • angular service-worker offline-app

Web developers come across scenarios like web application completely breaks when workstation goes offline. Likewise to get into our application, every time we need to open a browser and then access it. Instead if it is in app, it will be easy to access for end-user. Push notifications similar to email client need to be done through web application. All these are addressed by a magic called service worker.

Read More


All About Multi-Provider Feature of Angular Version 2.0

  • angular dependency-injection multi-providers

The newly introduced concept of dependency injection in Angular version 2.0 makes it an attractive front-end technology all because of one amazing feature called 'Multi-Providers'. In general, it allows the users to attach certain operations by themselves and a few plugin custom functionality which is not required in our mobile app use case.

Read More


JHipster - Generate simple web application code using Spring Boot and Angular

  • jhipster spring-boot angular web-application

JHipster is one of the full-stack web app development platform to generate, develop and deploy. It provides the front end technologies options of React, Angular, Vue mixed with bootstrap and font awesome icons. Last released version is JHipster 6.0.1. It is licensed under Apache 2 license.

Read More


8 Reasons Why Python Scores Over PHP for Web Development

  • python php web-development

PHP, the general-purpose scripting language has been used since decades for socket programming and web development. But in recent times, Python has become the most sought after programming language. This all-purpose programming language is attracting more developers in the industry owing to its highly dynamic and extensible nature. Let's see how Python is winning over age-old PHP.

Read More


Exonum Blockchain Framework by the Bitfury Group

  • blockchain bitcoin hyperledger blockchain-framework

Exonum is an extensible open source blockchain framework for building private blockchains which offers outstanding performance, data security, as well as fault tolerance. The framework does not include any business logic, instead, you can develop and add the services that meet your specific needs. Exonum can be used to build various solutions from a document registry to a DevOps facilitation system.

Read More


mkcert - No config certificate authority tool

  • certificate ssl security cert go go-lang

Mkcert is go-lang project, which is super easy tool to setup certificate authority without any configuration. Using certificates are inevitable these days, data should be transferred in a secure communication channel. Buying a certificate is expensive and mostly companies buy certificates only for production systems. In Dev setup, if we use self-signed certificate then there will be trust errors. mkcert automatically creates and installs a local CA in the system root store, and generates locally-trusted certificates.

Read More


Scene.js - Library to Create Timeline-Based Animation

  • scenejs css timeline javascript animation motion

Scene.js is a JavaScript timeline-based animation library for creating animation websites. As an animated timeline library, it allows you to create a chronological order of movements and positions of objects.

Read More


AbanteCart - Easy to use open source e-commerce platform, helps selling online

  • e-commerce ecommerce cart

AbanteCart is a free, open source shopping cart that was built by developers with a passion for free and accessible software. Founded in 2010 (launched in 2011), the platform is coded in PHP and supports MySQL. AbanteCart’s easy to use admin and basic layout management tool make this open source solution both easy to use and customizable, depending on the skills of the user. AbanteCart is very user-friendly, it is entirely possible for a user with little to no coding experience to set up and use this cart. If the user would be limited to the themes and features available in base AbanteCart, there is a marketplace where third-party extensions or plugins come to the rescue.

Read More


Appserver.io – The First Multithreaded Application Server for PHP written in PHP

  • appserver application-server php

What if you could reliably run PHP without Nginx or Apache, but also without relying on its internal server? What if you could do async operations in PHP with true multi threading, fully taking advantage of multi core processors without hacks or a jungle of callbacks? What if you had drag and drop installation support for your PHAR packaged web apps in an environment identical to its production counterpart? Welcome to appserver.io – the worlds first open source application server for PHP.

Read More


GlobalSign - Free Certificate for Open Source Projects

  • free certificate ssl security

GlobalSign is one of the Internet’s original trust service providers (technically known as Certificate Authorities). They have issued millions of trusted Digital Certificates to people, servers and mobile devices for Public Key Infrastructure (PKI) enabled solutions and applications. They are now giving certificates for free for open source projects.

Read More


Holistic usage guide for OpenSSL

  • openssl security certificate tools

OpenSSL is a general purpose cryptographty toolkit that provides an open source implementation of Transport Layer Security(TLS) and Secure Socket Layer(SSL) protocols. It is written in C,assembly and Perl language but wrappers are available in all languages. This article explains about OpenSSL commands.

Read More


Electron JS- Native capabilities

  • electronjs electron desktop-app

Electron is an open source library to build native applications which also works as cross-platform desktop applications. It provision operating system functionalities with help of node integration. In this article, we will go through how to access the Operating System variables, Inter system communication, System dialog, Access files, folders also their statistics.

Read More