简体   繁体   中英

Redirect If Token Not Valid

I am using Angular2 and Auth0 for authentication. I can see the token is being stored into local storage. I am writing a function in my auth.service.ts file to check for a valid token then calling that function on init in the component. I have tried many different variations of this function but cannot get the app to validate correctly.

After I login it forwards me back to the home page even when I do login and retrieve a valid token.

My goal is to not allow access to this page without a valid token. But when there is a valid token allow access to this page.

This is what I have tried currently,

auth.service.ts

import { Injectable }                      from '@angular/core';
import { Router, CanActivate }             from '@angular/router';
import { tokenNotExpired, JwtHelper }      from 'angular2-jwt';
import { myConfig }                        from './auth.config';

// Avoid name not found warnings
declare var Auth0Lock: any;

var options = {
    theme: {
    logo: '../assets/img/logo.png',
    primaryColor: '#779476'
    },
    auth: {
    responseType: 'token',
    redirect: true,
    redirectUrl: "http://localhost:3000/dashboard",
    },
    languageDictionary: {
    emailInputPlaceholder: "email@example.com",
    title: "Login or SignUp"
  }, 
 };

@Injectable()
export class Auth {

  // Configure Auth0
  lock = new Auth0Lock(myConfig.clientID, myConfig.domain, options,{});

  constructor(private router: Router ) {
    // Add callback for lock `authenticated` event
    this.lock.on('authenticated', (authResult) => {
      localStorage.setItem('jwtToken', authResult.idToken);
    });
  }

   public login() {
    this.lock.show();
  };

  public authenticated() {
    return tokenNotExpired();
  };

  public isAuthenticated(): boolean {
    try {
        var jwtHelper: JwtHelper = new JwtHelper();
        var token = this.accessToken;
        if (jwtHelper.isTokenExpired(token))
            return false;
        return true;
    }
    catch (err) {
        return false;
    }
  }

  private get accessToken(): string {
        return localStorage.getItem('jwtToken');
    }

  public logout() {
    localStorage.removeItem('jwtToken');
  };
}

guard.service.ts

import { Injectable }                      from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Auth }                 from './auth.service';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class Guard implements CanActivate {

    constructor(protected router: Router, protected auth: Auth ) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
        if (state.url !== '/pages/home' && !this.auth.isAuthenticated()) {
            this.auth.logout();
            this.router.navigate(['/pages/home']);
            return false;
        }
        return true;
    }
}

app.routing.ts

import {Guard}                          from "./services/guard.service";

const appRoutes: Routes = [
    {
        path: '',
        redirectTo: 'pages/home',
        pathMatch: 'full',
    },
    {
        path: '',
        component: FullLayoutComponent,
        canActivate: [Guard],
        data: {
            title: 'Home'
        },
        children: [
            {
                path: 'dashboard',
                component: DashboardComponent,
                data: {
                    title: 'Dashboard'
                }
            },

app.module.ts

import { Guard }                        from "./services/guard.service";
import { Auth }                         from "./services/auth.service";

providers: [ 
    Guard,
    Auth 
    ],

right way to achieve this to use Guards

    import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from './authService';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(protected router: Router, protected authService: AuthService) {

    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {

        if (state.url !== '/login' && !this.authService.isAuthenticated()) {
            this.authService.logOut();
            this.router.navigate(['/login']);
            return false;
        }

        return true;
    }
}

And in you rotes set

 path: 'admin',
        component: AdminPages.AdminPagesComponent,
        canActivate: [AuthGuard],
        children: [
            {
                path: 'dashboard',
                component: Dashboard,
                data: {
                    menu: {
                        title: 'Dashboard',
                        icon: 'ion-android-home',
                        selected: false,
                        expanded: false,
                        order: 0
                    }
                }
            },

authservice

public isAuthenticated(): boolean {
    try {
        var jwtHelper: JwtHelper = new JwtHelper();
        var token = this.accessToken;
        if (jwtHelper.isTokenExpired(token))
            return false;
        return true;
    }
    catch (err) {
        return false;
    }
}

public logOut(): void {
    localStorage.removeItem("access_token");
}

private get accessToken(): string {
        return localStorage.getItem('access_token');
    }



 private saveJwt(jwt): void {
        if (jwt) {
            localStorage.setItem('access_token', jwt)
        }        
    }
    public login(loginModel: LoginModel): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            var username = loginModel.email;
            var password = loginModel.password;
            var creds =
                "username=" + username + "&password=" + password + "&client_id=" + this.clientId + "&grant_type=" + this.grant_type;
            var headers = new Headers();
            headers.append('Content-Type', 'application/x-www-form-urlencoded');
            this.httpClient.post(this.identityServerUrl + "/connect/token", creds, { headers })
                .toPromise()
                .then(response => {
                    this.saveJwt(response.json().access_token);
                    resolve();
                })
                .catch(err => {
                    reject(err.json().error_description)
                });
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM