Angular redirect to login page

后端 未结 7 2243
盖世英雄少女心
盖世英雄少女心 2020-11-27 09:39

I come from the Asp.Net MVC world where users trying to access a page they are not authorized are automatically redirected to the login page.

I am trying to reproduc

7条回答
  •  醉酒成梦
    2020-11-27 09:56

    1. Create a guard as seen below. 2. Install ngx-cookie-service to get cookies returned by external SSO. 3. Create ssoPath in environment.ts (SSO Login redirection). 4. Get the state.url and use encodeURIComponent.

    import { Injectable } from '@angular/core';
    import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from 
      '@angular/router';
    import { CookieService } from 'ngx-cookie-service';
    import { environment } from '../../../environments/environment.prod';
    
    @Injectable()
    export class AuthGuardService implements CanActivate {
      private returnUrl: string;
      constructor(private _router: Router, private cookie: CookieService) {}
    
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        if (this.cookie.get('MasterSignOn')) {
          return true;
        } else {
          let uri = window.location.origin + '/#' + state.url;
          this.returnUrl = encodeURIComponent(uri);      
          window.location.href = environment.ssoPath +  this.returnUrl ;   
          return false;      
        }
      }
    }
    

提交回复
热议问题