- 在Angular应用中创建一个AuthGuard服务,该服务会检查用户是否已登录并授权访问受保护的路由。
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable | Promise | boolean | UrlTree {
if (this.authService.isAuthenticated()) {
return true;
}
// If not authenticated, redirect to login page
this.router.navigate(['/login']);
return false;
}
}
- 在应用中设置路由保护,当用户尝试访问受保护的路由时会触发AuthGuard服务中的canActivate方法。例如,以下代码演示了如何保护具有“/dashboard”路径的路由。
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './auth.guard';
import { DashboardComponent } from './dashboard/dashboard.component';
const routes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
- 在ASP.NET Core应用中实现基于JWT的身份验证,可以使用ASP.NET Core身份验证和授权组件或第三方库(如IdentityServer)来实现。以下示例演示了如何在ASP.NET Core中使用JwtBearer中间件实现身份验证。
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[