Authentication in Angular: A Practical Guide
Published: 2022-10-12 09:56:50

## What is Angular?

Angular is a framework that you can use to build single-page client applications with HTML and TypeScript. It implements functionality as well-integrated TypeScript libraries that you can import into an application. It includes many features, including forms management, routing, and client-server communication. 

The main benefit of using Angular is that, like all frameworks, it provides a consistent structure that eliminates the need to rebuild code from scratch. Since Angular is a component-based framework, it has the extra advantage of helping build scalable web applications, allowing you to import features easily. It saves time and boosts performance and efficiency. It also provides tools that help develop, build, test, update code, and [upload files to Angular applications](https://cloudinary.com/blog/file_upload_with_angular_or_angularjs_to_cloudinary).

## What is Authentication?

Authentication technology implements access control for systems by requiring users to prove their identity. It checks a user's credentials against those in a data authentication server or a database of authorized users to ensure they match. This process protects resources and helps ensure compliance with enterprise information security standards and regulatory requirements.

Organizations use [various authentication methods](https://frontegg.com/blog/authentication) to secure networks, allowing only authenticated users and processes to access protected resources, such as networks, computer systems, databases, network-based applications and services, and websites.

A user or process that passes the authentication process is subjected to an authorization process that determines if the authenticated entity has permission to access a certain protected resource. It means a user can succeed in authenticating but fail to get authorization to access a certain resource.

## Quick Tutorial: Adding Authentication to an Angular Application

Angular has a built-in [Route Guards](https://angular.io/guide/router) feature to restrict user navigation to other in-app components. It allows developers to involve authentication or permissions in routing and control what kind of users can access certain app parts. The navigation can continue If a route guard returns true, and access is denied if returned false. They can also return another route/path for redirection.  

Angular provides pre-built interfaces for developing these route guards, and developers need to add functionality to them. For example, here is a route guard that implements a _demoLoginService_ and gives access after checking if the user is logged in:

`@Injectable()
export class AuthGuard implements CanActivate {
   constructor(public service: demoLoginService, public router: Router{
   }
   canActivate(): boolean | UrlTree {
       return this.service.isUserLoggedIn() ||
              this.router.parseUrl('login');
   }
}`

Here, the _canActivate()_method returns true if the user is logged in. Otherwise, it returns a _UrlTree_ to redirect the user back to login. Further information about this guard is in the config that is usually in the _app.routing.ts_ file: 

`const appRoutes: Routes = [
  { 
    path: '', component: demoStoreComponent
  },{ 
    path: 'checkout', 
    component: demoCheckoutComponent, 
    canActivate: [AuthGuard]
  },{
    path: 'login', component: demoLoginComponent
  }
];`

This routing specifies which component and route the guard is protecting, d_emoCheckoutComponent_ and /_checkout_ here. All other routes are public, like /login.
Multiple Route Guards

Multiple guards can protect a single route. For multiple routes, the _canActivate_ property for a component in the config has to be provided with an array of guards:

`{
    path: 'admin', 
    component: demoAdminComponent, 
    canActivate: [AuthGuard, AdminRoleGuard]
},  `

Here, the _AuthGuard_ route guard checks the login status of a user and redirects if they aren’t logged in. Meanwhile, _AdminRoleGuard_ checks if the user is an administrator and redirects to an error screen if they aren’t.
Types of Route Guards
Angular provides different kinds of route guards. Combining multiple different guards enables enforcing complex authentication and permissions for components.

For example, the C_anActivateChild_ component functions similar to _CanActivate_, but it runs before a child route gets activated:

`{     
   path: 'admin',     
   component: demoAdminComponent,     
   canActivate: [AuthGuard],     
   children: [       
      { 
        path: ''
        canActivateChild: [AuthGuard],
        children: [... ]   
      }
   ]
}`

Here, the child components of the _demoAdminComponent_ are specified along with the guard protecting them. 

Another example is _CanDeactivate_ which performs the opposite function of _CanActivate_. However, it doesn’t let the user navigate away from the current page. There is also the _CanLoad_ guard for routes that use lazy-loading. The guard can stop the component’s code from loading if the user is never supposed to access them in the first place: 

`{         
   path: 'team/:id',         
   component: TeamDemoComponent,         
   loadChildren: () => import('./team').then(mod => mod.TeamModule),        
   canLoad: [CanLoadTeamSection]       
}`