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

Angular中如何判断用户登录状态并实现路由守卫?

Angular + Apollo Client 路由守卫实现(基于HttpOnly Cookie)

问题核心

依赖HttpOnly Cookie做身份校验,无法通过前端存储判断登录状态,只能通过GraphQL请求验证用户是否已登录,但原代码的同步写法无法等待异步请求结果,导致守卫逻辑失效。

修正方案

1. 修改AuthService,返回异步Observable

将isLogged改为返回Observable<boolean>,通过GraphQL请求结果判断登录状态:

// auth.service.ts
import { Injectable } from '@angular/core';
import { MyAccountGQL } from './generated/graphql';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class AuthService {
  private redirectUrl: string;

  constructor(private myAccountGQL: MyAccountGQL) {}

  isLogged(): Observable<boolean> {
    // 发起单次GraphQL查询验证用户身份
    return this.myAccountGQL.fetch().pipe(
      // 存在用户数据且无错误则判定已登录
      map(({ data, error }) => !!data?.myAccount && !error),
      // 请求失败(如401未授权)直接返回未登录状态
      catchError(() => of(false))
    );
  }

  setRedirectUrl(url: string): void {
    this.redirectUrl = url;
  }

  getRedirectUrl(): string {
    return this.redirectUrl;
  }
}

2. 调整AuthGuard,处理异步流

守卫需要返回Observable,让Angular等待请求完成后再决定路由是否激活:

// auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { AuthService } from './auth.service';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean | UrlTree> | boolean | UrlTree {
    return this.checkLogin(state.url);
  }

  private checkLogin(url: string): Observable<boolean | UrlTree> {
    return this.authService.isLogged().pipe(
      map(isLoggedIn => {
        if (isLoggedIn) {
          return true;
        }
        // 未登录时记录目标URL,跳转登录页
        this.authService.setRedirectUrl(url);
        return this.router.parseUrl('/login');
      })
    );
  }
}

3. 关键配置:确保Apollo Client携带Cookie

在Apollo Client配置中开启withCredentials,否则请求不会自动带上HttpOnly Cookie:

// app.module.ts 或 Apollo配置文件
import { NgModule } from '@angular/core';
import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';

@NgModule({
  imports: [ApolloModule, HttpLinkModule],
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: (httpLink: HttpLink) => ({
        link: httpLink.create({
          uri: '/your-graphql-endpoint',
          withCredentials: true // 必须开启,确保Cookie随请求发送
        }),
        cache: new InMemoryCache()
      }),
      deps: [HttpLink]
    }
  ]
})
export class GraphQLModule {}

逻辑说明

  • isLogged使用fetch()发起单次请求,而非watch()(后者用于监听数据变化),仅做一次身份校验。
  • 守卫返回Observable后,Angular会自动等待请求完成,解决了原代码无法等待响应的问题。
  • 捕获请求错误(如401)直接判定为未登录,覆盖服务器返回错误的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 20:01:11