Angular 路由包括身份验证保护和重定向

Angular routing including auth guard and redirections

我有一个 angular 应用程序,想实现客户端路由。我有 3 个组件:loginchatadmin。访问管理员和聊天受到 auth guard 的限制。理想情况下 路由行为应该是 :

我几乎正确地设置了重定向,但是单击登录时的重定向仍然取决于我单击的位置 before/last。这意味着如果用户单击登录,它将转到登录,成功登录后,它将重定向到聊天。然后用户注销并单击登录,它转到登录但重定向到聊天而不是管理员,这是我不想要的。无论过去哪个路由处于活动状态,点击登录都应始终转到管理员。

我怎样才能做到这一点?

谢谢。

app.component

<nav>
  <ol>
    <li><a routerLink="/login">Login</a></li>
    <li><a routerLink="/admin">Admin</a></li>
    <li><a routerLink="/chat">Chat</a></li>
  </ol>
</nav>
<router-outlet></router-outlet>
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
}

登录组件

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import {AuthService} from "../auth.service";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  email: string;
  password: string;
  loginMessage: string;
  loginForm: FormGroup;

  constructor(
    private http: HttpClient,
  ) { }

  ngOnInit() {
    this.loginForm = new FormGroup({
      'email': new FormControl(this.email, [
        Validators.required,
        Validators.email
      ]),
      'password': new FormControl(this.password, [
        Validators.required,
        Validators.minLength(2)
      ])
    });
    console.log('init');
  }
  logout(): void {
    this.authService.loggedIn = false;
  }
  login(): void {
    if (!this.isValidInput()) { return; }

    const data = {email: this.email, pass: this.password};
    this.authService.login('localhost:3000/login', data).subscribe((response: any) => {
      this.loginForm.reset();
      this.authService.loggedIn=true;
      let redirect = this.authService.redirecturl ? this.router.parseUrl(this.authService.redirecturl) : '/admin';
      this.router.navigateByUrl(redirect);  
    });
  }

  isValidInput(): Boolean {
    if (this.loginForm.valid) {
      this.email = this.loginForm.get('email').value;
      this.password = this.loginForm.get('password').value;
      return true;
    }
    return false;
  }
}
<form [formGroup]="loginForm">
  <!-- this div is just for debugging purpose -->
  <div id="displayFormValues">
    Value: {{loginForm.value | json}}
  </div>

  <label for="email"><b>Email</b></label>
  <input id="email" type="email" formControlName="email" email="true" required>
  <label for="password"><b>Password</b></label>
  <input id="password" type="password" formControlName="password" required>
  <button (click)="login()" routerLink="/admin" routerLinkActive="active">Login</button>
  <div id="loginMessage">{{loginMessage}}</div>
</form>

管理组件

<p>admin works!</p>
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

聊天组件

<p>chat works!</p>
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-chat',
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.css']
})
export class ChatComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

authgauard

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

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor() {
  }

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

    if (this.authService.isLoggedIn()) {
      return true;
    } else {
      this.authService.redirecturl = url;
      this.router.navigate(['/login']);
      return false;
    }
  }

}

应用路由模块

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ChatComponent } from './chat/chat.component';
import { AdminComponent } from './admin/admin.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';

const routes: Routes = [
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: 'admin',
    component: AdminComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'chat',
    component: ChatComponent,
    canActivate: [AuthGuard]
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes, {enableTracing: true})],
  exports: [RouterModule]
})
export class AppRoutingModule { }

授权服务

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { throwError, Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  redirecturl: string; // used for redirect after successful login
  username: string;
  loginMessage: string;
  greeting = 'Hello guest!';
  loggedIn = false;
  config = {
    serverHost: 'localhost',
    serverPort: 3000,
    loginRoute: 'login',
    standardGreeting: `Hello guest!`,
    standardUsername: 'Guest'
  };

  constructor(private http: HttpClient) { }

  login(loginUrl: any, body: { pass: string }) {
    return this.http.post(loginUrl, body, httpOptions)
      .pipe(
        catchError(this.handleError)
      );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    return throwError(
      'Something bad happened; please try again later.');
  }

  isLoggedIn(): boolean {
    return this.loggedIn;
  }
  }
}

不要在 html 中执行此操作 <button (click)="login()" routerLink="/admin" routerLinkActive="active">Login</button>,而是像这样在打字稿中放置重定向 url。

    login(): void {
        if (!this.isValidInput()) { return; }

        const data = {email: this.email, pass: this.password};
        this.authService.login('localhost:3000/login', data).subscribe((response: any) => { 
       if(response.isSuccess){
          this.loginForm.reset();
          this.authService.loggedIn=true;
           if(!this.authService.redirectUrl){
            this.router.navigateByUrl('/admin');  
            } else{
             this.router.navigateByUrl(this.authService.redirectUrl);  
            }
         }
        });
      }

如果您导航到登录 URL 那么请删除 redirectUrl 否则它将始终重定向到上次访问的页面。

编辑

在 App.component.html 中,您正在使用 routerlink 导航登录,而不是使用此

<nav>
  <ol>
    <li><a (click)='redirectToLogin()'>Login</a></li>
    <li><a routerLink="/admin">Admin</a></li>
    <li><a routerLink="/chat">Chat</a></li>
  </ol>
</nav>
<router-outlet></router-outlet>

并在 app.component.ts 中使用此

redirectToLogin(){
    this.authService.redirectUrl = null;
    this.router.navigateByUrl('/login');
}