代码之家  ›  专栏  ›  技术社区  ›  Alavaros

刷新Angular 6项目的页面时出现403错误

  •  0
  • Alavaros  · 技术社区  · 6 年前

    我在AWS Elastic Beanstalk中部署了一个带有JWT授权的angular6项目,并使用CloudFront,我使用@auth0/angularjwt库来管理它。一切正常,我有一个链接到我的页面,其中附加了一个授权令牌到请求:

    https://myapp.com/?authorization=my_token
    

    这由我的AuthGuard服务处理:

    ...
    canActivate(
      next: ActivatedRouteSnapshot,
      state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
      const token = next.queryParams[AUTHORIZATION_PARAMETER];
      if (token) {
        this.authService.login(token);
      }
    
      if (!this.authService.isLoggedIn()) {
        this.router.navigate(['login']);
        return false;
      }
    
      return true;
    }
    ...
    

    我同意:

    export const AppRoutes: Routes = [
      { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
      { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }
    ];
    

    ...
    private jwtHelper: JwtHelperService;
    private userAuthenticated: BehaviorSubject<boolean> = new BehaviorSubject(false);
    
    constructor(
      private authStore: AuthStore
    ) {
      this.jwtHelper = new JwtHelperService();
    }
    
    login(token: string) {
      this.authStore.setToken(token);
      this.updateState();
    }
    
    logout() {
      this.authStore.clearToken();
      this.updateState();
    }
    
    isLoggedIn(): boolean {
      this.updateState();
      return this.userAuthenticated.getValue();
    }
    
    updateState() {
      this.userAuthenticated.next(this.isTokenValid());
    }
    
    isTokenValid(): boolean {
      const token = this.getAsyncToken();
      return !this.jwtHelper.isTokenExpired(token);
    }
    
    getAsyncToken() {
      return this.authStore.getToken();
    }
    ...
    

    在我的AuthStore中:

    ...
    setToken(token: string) {
      localStorage.setItem(JWT_TOKEN_STORAGE_KEY, token);
    }
    
    getToken() {
      return localStorage.getItem(JWT_TOKEN_STORAGE_KEY);
    }
    
    clearToken() {
      localStorage.removeItem(JWT_TOKEN_STORAGE_KEY);
    }
    ...
    

    因此,当我单击链接时,应用程序将正确加载仪表板组件,并按以下方式更改URL:

    https://myapp.com/dashboard
    

    在此之后,如果按F5键刷新页面,则会出现以下错误:

    <Error>
      <Code>AccessDenied</Code>
      <Message>Access Denied</Message>
      <RequestId>the_request_id</RequestId>
      <HostId>the_host_id</HostId>
    </Error>
    

    更新: 这是一个与CloudFront相关的问题,资源“dashboard”不存在,所以它返回一个拒绝访问的消息,如何在这个过程中防止/管理这类事件(F5键)?

    1 回复  |  直到 6 年前