Using secure routing

With our authentication in place, we want to ensure that users cannot bypass it just by typing in the URL of the page. We wouldn't have much security set up if users could easily bypass it, especially after we went to all the trouble of providing secure authorization. What we are going to do is put another service in place that the router will use to determine whether it can activate the route. First, we create the service, as follows:

ng g s services/Authorization

The service itself is going to implement the CanActivate interface, which the router will use to determine whether the route can be activated. The constructor for this service simply takes in the router and our OauthAuthorizationService service:

export class AuthorizationService implements CanActivate {
constructor(private router: Router, private authorization: OauthAuthorizationService) {}
}

The boilerplate code for the canActivate signature looks a lot more complicated than it needs to for our purposes. What we are really going to do here is check the authentication status and, if the user is not authenticated, we will reroute the user back to the general page. If the user is authenticated, we return true and the user continues on to the secured page:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (!this.authorization.IsAuthenticated) {
this.router.navigate(['general']);
return false;
}
return true;
}

We have two routes that we are going to follow here, as we saw in the navigation links. Before we add our routes, let's create the components that we are going to show:

ng g c components/GeneralChat
ng g c components/SecretChat

Finally, we have reached the point where we are going to hook up the routes. As we saw in the previous chapter, adding routes is straightforward. The secret sauce that we are going to add is canActivate. With that in our route, the user cannot bypass our authentication:

const routes: Routes = [{
path: '',
redirectTo: 'general',
pathMatch: 'full'
}, {
path: 'general',
component: GeneralchatComponent
}, {
path: 'secret',
component: SecretchatComponent,
canActivate: [AuthorizationService]
}];
Even though we have to supply a callback URL in our Auth0 configuration, we don't include it in our routes because we want to control the page—we do it to navigate to and from our authorization service.

At this point, we want to start writing messages from the client to the server and receive messages from it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.104.29