angularamazon-web-servicesangular-routingangular2-jwt

Getting 403 error when refresh the page of my Angular 6 project


I have an Angular 6 project with JWT authorization deployed in AWS Elastic Beanstalk and using CloudFront, which I manage with @auth0/angular-jwt library. Everything works fine, I have a link to my page which append an authorization token to the request:

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

This is treated by my AuthGuard service:

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

In my AppRoutes:

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

In my 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();
}
...

In my 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);
}
...

So when I click on the link, the app loads correctly the dashboard component, and change the URL like this:

https://myapp.com/dashboard

Once here, if I press the F5 key to refresh the page, I get this error:

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

Thanks in advance.

UPDATE: It's a problem related to CloudFront, the resource "dashboard" doesn't exist so it returns an Access Denied, how to prevent/manage these kinds of events (F5 key) in angular?


Solution

  • This issue can be resolved by handling url rewriting on server side.

    Check the documentation under Development servers on page https://angular.io/guide/deployment

    You may get help from below links

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

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