【问题标题】:Getting 403 error when refresh the page of my Angular 6 project刷新我的 Angular 6 项目的页面时出现 403 错误
【发布时间】:2018-09-19 11:00:56
【问题描述】:

我有一个带有 JWT 授权的 Angular 6 项目,部署在 AWS Elastic Beanstalk 中并使用 CloudFront,我使用 @auth0/angular-jwt 库进行管理。一切正常,我有一个指向我的页面的链接,该链接将授权令牌附加到请求中:

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;
}
...

在我的 AppRoutes 中:

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

在我的 AuthService 中:

...
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 相关的问题,资源“仪表板”不存在,因此它返回访问被拒绝,如何防止/管理这些类型的事件(F5 键)角度?

【问题讨论】:

    标签: angular amazon-web-services angular-routing angular2-jwt


    【解决方案1】:

    这个问题可以通过在服务器端处理url重写来解决。

    查看以下文档 开发服务器在页面https://angular.io/guide/deployment

    您可以通过以下链接获得帮助

    https://codeburst.io/deploy-angular-2-node-js-website-using-aws-1ac169d6bbf

    https://aws.amazon.com/premiumsupport/knowledge-center/s3-website-cloudfront-error-403/

    【讨论】:

    • 这正是我必须做的。我将 CloudFront 配置为在发生 404 Not Found 错误时发送 200 OK 响应并重定向到路径“/index.html”。
    猜你喜欢
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 2013-01-25
    • 2019-01-10
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多