1

我试图通过定义路由保护并将 canActivate 分配给每个想要安全的路由来保护我的应用程序免受未经授权的用户的攻击。这些路由一切正常,例如,当有人想从 url 访问路由时,它将自动重定向到登录页面,除非他/她已登录,然后应用程序将重定向到特定路由。但是有一种路线,当用户登录时,它总是返回登录页面。路由出现这个问题'/verify/:idC',怎么办?

路由.ts:

{ path: 'verify/:idC', component: VerifyRoleComponent, canActivate: [AuthGuard] },

auth-guard.ts:

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { AuthService } from '../auth/auth.service';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService, private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : boolean {
    let url: string = state.url;

    return this.checkLogin(url);
  }

  checkLogin(url: string): boolean {
    if (this.authService.isLoggedIn) { return true; }

    // Store the attempted URL for redirecting
    this.authService.redirectUrl = url;

    // Navigate to the login page with extras
    this.router.navigate(['/login']);
    return false;
  }

}

auth.service.ts:

@Injectable()
export class AuthService {

  isLoggedIn = false;

  constructor() { }

  // store the URL so we can redirect after logging in
  redirectUrl: string;

  login(): Observable<boolean> {
    return Observable.of(true).delay(1000).do(val => this.isLoggedIn = true);
  }

  logout(): void {
    this.isLoggedIn = false;
  }

}

验证组件.ts:

@Component({
  selector: 'app-verify-role',
  templateUrl: './verify-role.component.html',
  styleUrls: ['./verify-role.component.scss']
})
export class VerifyRoleComponent implements OnInit {

  auth: Auth;

  constructor(private credService: CredentialService, private authService: AuthService,
    private route: ActivatedRoute,
    private router: Router) { }

  ngOnInit() {    
    const id = this.route.snapshot.paramMap.get('idC');
    console.log(id) ;

    this.route.paramMap
      .switchMap((params: ParamMap) => 
        this.credService.getAccountId(params.get('idC')))
          .subscribe(res => {
            this.auth = res;
            console.log(this.auth);
            if (res.role.toString() == "User"){
              let idC = res.account;
              this.loginUser(idC);
            } else {}
          }, err => {
            console.log(err);
        });
  }

  loginUser(idC:string) {
    this.authService.login().subscribe(() => {
      if (this.authService.isLoggedIn) {
        let redirect = this.authService.redirectUrl ? this.authService.redirectUrl : '/profile/'+idC;
        this.router.navigate([redirect]);
      }
    });
  }

}
4

1 回答 1

1

我认为您必须先添加一个 elsethis.router.navigate(['/login']);

于 2018-08-27T14:16:54.087 回答