Up next

Angular Router Guards for Firebase Users

0 Views· 09/19/24
Questy
Questy
1 Subscribers
1
In

UPDATE: Get the latest version here https://angularfirebase.com/le....ssons/google-user-au

Router Guards are used in Angular to prevent unauthorized users from navigating anywhere they want in your app. At this point our app has a working Firebase authentication system, but any visitor can access routes intended for only logged in users.

Guards handle this problem by implementing the CanActivate interface, which tells Angular whether or not to activate a route. In this example, we will protect pages for unauthenticated users and redirect them to a signin page.

Step 1 - Generate the Guard

We use the CLI in Angular 4 to generate a default guard.

Guards use the injectable decorator, so they need to be registered as a provider just like any other service in the app module.

Step 2 - Update the Auth Service

Our users are authenticating via Firebase and the AngularFire2 package. In the service we are subscribing the FirebaseAuthState, then using a getter to see if the auth object is null. Checkout the OAuth tutorial for more details on this code.

Step 3 - Implement the Guard Logic

Router guards always return a boolean type or boolean observable. The logic here is simple, if the FirebaseAuthState is defined, we activate the route. Otherwise, we return false and navigate to to the login page.

Now that the guard is complete, we just need to apply it to specific routes in the routing module.

That's it for router guards, I'll see you next time.

Show more

 0 Comments sort   Sort By


Up next