1

我有一个 Angular 6 项目,其 JWT 授权部署在 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 键)角度?

4

1 回答 1

3

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

于 2018-09-19T12:34:36.113 回答