sureshchahal / angular2-adal

Angular 2 wrapper for adal.js
MIT License
41 stars 50 forks source link

Implement AuthGaurds #11

Open sureshchahal opened 8 years ago

sureshchahal commented 8 years ago

Need Authgaurd so that routing to protected views can be implemented

isaacrlevin commented 7 years ago

I was able to do this without much effort (though I may have done it wrong). I wrapped AdalService with my own AuthContext and used that in Auth Guard

auth-context.service.ts `import { Injectable } from '@angular/core' import { Observable } from 'rxjs/Observable' import { Observer } from 'rxjs/Observer' import { Http, Headers, Response, RequestOptions } from '@angular/http' import { AdalService, AuthHttp, OAuthData } from 'ng2-adal/services';

@Injectable() export class AuthContext {

public userInfo: OAuthData
constructor(private adalService: AdalService, private authHttp: AuthHttp) {
    this.adalService.init(this.adalConfig);
    this.adalService.handleWindowCallback();
    if (this.adalService.userInfo.isAuthenticated) {
        this.userInfo = this.adalService.userInfo;
    }
}

public handleWindowCallback() {
    this.adalService.handleWindowCallback();
}

public getUser(): Observable<any> {
    return this.authHttp.get('/api/admin')
        .map((response: Response) =>
            response.json());
}

private get adalConfig(): any {
    return {
        // SINGLE TENANT SUPPORT, IF NOT SPECIFIED IT IS MULT
        tenant: 'monsterenergycorp.onmicrosoft.com',
        clientId: '9a9718e2-0836-49dc-88b3-a79d203e8949',
    };
}

login() {
    this.adalService.login();
}
logOut() {
    this.adalService.logOut();
}

}`

authentication.guard.ts

`import { Injectable } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild } from '@angular/router'; import { AuthContext } from './auth-context.service';

@Injectable() export class AuthGuard implements CanActivate { constructor(private router: Router, private authContext: AuthContext) { }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    // Check to see if a user has a valid JWT
    if (this.authContext.userInfo !== undefined && this.authContext.userInfo.isAuthenticated) {
        // If they do, return true and allow the user to load the home component
        return true;
    }
    // If not, they redirect them to the login page
    this.router.navigate(['/login']);
    return false;
}

canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return this.canActivate(route, state);
}

}`

And then I reference that guard in my routes

`import { Routes } from '@angular/router'; import { ErrorComponent } from './error/error.component'; import { AuthGuard } from './authentication/authentication.guard'

export const ROUTES: Routes = [ { path: '', redirectTo: 'app/pricingreview', pathMatch: 'full' }, { path: 'app', canActivate: [AuthGuard], loadChildren: () => System.import('./layout/layout.module') } ];`

And then the children of app

`import { Routes, RouterModule } from '@angular/router'; import { Layout } from './layout.component'; import { AuthGuard } from './../authentication/authentication.guard' // noinspection TypeScriptValidateTypes const routes: Routes = [ { path: '', component: Layout, children: [ { path: '', redirectTo: 'dashboard', pathMatch: 'full', canActivateChild: [AuthGuard], }, { path: 'dashboard', loadChildren: () => System.import('../dashboard/dashboard.module'), canActivateChild: [AuthGuard], }, { path: 'id_token', loadChildren: () => System.import('../dashboard/dashboard.module'), canActivateChild: [AuthGuard], }, { path: 'inbox', loadChildren: () => System.import('../inbox/inbox.module'), canActivateChild: [AuthGuard], } ] } ];

export const ROUTES = RouterModule.forChild(routes); `

Hope all this makes sense