Today on the show we explore securing Angular 2 routes. And we’ll use OAuth, Firebase and Google (or your preferred OAuth provider) to get us there.

You can grab the source on the GitHub Repo.

Don’t forget to Subscribe to my Fresh Bytecode channel for regular Java/Web-related screencasts

Here’s the script if you’d like to follow along at home!

[ ] Discuss the plan for today - use Google authentication to login to your app. Pluck Image URLs along the way.

[ ] Check out last weeks show to get up to speed on the QOTD app

[ ] Turn on authentication in your application (auth/signin method)

[ ] Configure your module to turn on authentication methods you prefer

export const firebaseAuthConfig = {
  provider: AuthProviders.Google,
  method: AuthMethods.Popup
}    

// and in imports...
AngularFireModule.initializeApp(firebaseConfig, firebaseAuthConfig),

[ ] Now to secure the routes in app.routing.ts

const appRoutes: Routes = [
    { path: '',  redirectTo: '/quotes',  pathMatch: 'full'},
    { path: 'quotes', component: QuotelistComponent, canActivate: [LoggedInGuard] },
    { path: 'login', component: LoginComponent }
];


export const appRoutingProviders: any[] = [
    LoggedInGuard
];

[ ] Implement login.guard.ts

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

@Injectable()
export class LoggedInGuard implements CanActivate {
    constructor(private loginService: LoginService, private router: Router) { }

    canActivate(): boolean {

        console.log("Guard function has been invoked");

        let authenticated = false;

        if (this.loginService.isAuthenticated) {
            authenticated = true;
        }
        else {
            this.router.navigate(['/login']);
        }
        console.log("Returning from Guard function with: " + authenticated);
        return authenticated;
    }
}

[ ] Explore the actual login service

[ ] Add some markup to the menu

<div class="right item" *ngIf='loginService.isAuthenticated'>
    <a class="item" >
        <img class="ui avatar image" [src]='loginService.photoUrl'>
        <span>{{ loginService.displayName }} </span>
        </a>
    </div>
    <div class="right item" *ngIf='!loginService.isAuthenticated'>
    <a class="ui inverted button" routerLink='/quotes'>Log in</a>
</div>

[ ] GitHub repo has localStorage to cache oAuth tokens

[ ] Next time we’ll look at editing values.