You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular的CanActivateFn守卫中校验HTTP-only Cookie

步骤1:创建Auth服务封装校验请求

先封装一个Auth服务来处理后端接口调用,避免在守卫内直接编写HTTP逻辑,遵循Angular依赖注入的最佳实践:

// auth.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class AuthService {
  private checkCookieUrl = 'http://localhost:8000/api/v1/login';

  constructor(private http: HttpClient) {}

  // 校验HTTP-only Cookie中的token
  checkAuthCookie(): Observable<boolean> {
    return this.http.get(this.checkCookieUrl, { withCredentials: true })
      .pipe(
        // 接口返回成功则判定认证通过
        map(() => true),
        // 捕获401/403或网络错误,统一返回认证失败
        catchError(() => of(false))
      );
  }
}

步骤2:实现CanActivateFn路由守卫

修改自动生成的loginAuthGuard,注入AuthService和Router完成校验逻辑:

// login-auth.guard.ts
import { CanActivateFn, Router } from '@angular/router';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';
import { map } from 'rxjs/operators';

export const loginAuthGuard: CanActivateFn = (route, state) => {
  const authService = inject(AuthService);
  const router = inject(Router);

  return authService.checkAuthCookie().pipe(
    map(isAuthenticated => {
      if (isAuthenticated) {
        return true;
      }
      // 认证失败时重定向到登录页(可根据实际需求修改路由路径)
      return router.createUrlTree(['/login']);
    })
  );
};

关键注意事项

  • withCredentials: true:必须开启该配置,否则浏览器不会自动携带HTTP-only Cookie到后端接口,跨域场景下该配置尤为重要。
  • 路由配置示例:在路由模块中使用该守卫保护需要认证的页面:
    // app-routing.module.ts
    import { loginAuthGuard } from './login-auth.guard';
    
    const routes: Routes = [
      {
        path: 'admin',
        component: AdminComponent,
        canActivate: [loginAuthGuard]
      },
      // 其他路由配置...
    ];
    

内容的提问来源于stack exchange,提问作者suer231232131133

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 13:42:05