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

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

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

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

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

最佳答案

这个问题可以通过在服务器端处理 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/

关于angular - 刷新 Angular 6 项目页面时出现 403 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52404363/

相关文章:

angular - Firebase i18n 重写语言覆盖 cookie 被忽略

amazon-web-services - ffmpeg硬编码字幕,无字幕但无输出错误

python - 如何在亚马逊商品 list 上获得正确的运费和税费?

amazon-web-services - (Kops)Kubernetes服务映射到AWS Route53中的DNS名称吗?

angular - 从子导出 Angular 导航到根?

Angular 发布请求期望 GET

javascript - 如何从 Angular 2/5 中的服务订阅对象?

angular - 在 routerLink 中设置 url 字符串

angular - typescript - 变量声明

angular - 仅在以 Angular 刷新页面后才会显示来自 api 的数据