DEV Community

Cover image for Authentication in Angular: A Practical Guide
Gilad David Maayan
Gilad David Maayan

Posted on

Authentication in Angular: A Practical Guide

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.

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 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 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]
}

Top comments (0)