Encountering a 403 error upon refreshing the page of my Angular 6 project

I am currently working on an Angular 6 project with JWT authorization deployed on AWS Elastic Beanstalk and utilizing CloudFront. I am using the @auth0/angular-jwt library to manage everything efficiently. The setup is functioning smoothly, and I have a link that directs to my page while appending an authorization token to the request:

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

This link is processed 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;
}
...

My AppRoutes configuration looks like this:

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

In my AuthService component:

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

Within my AuthStore module, I handle the token management as follows:

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

When clicking on the provided link, the application successfully loads the dashboard component and updates the URL to:

https://myapp.com/dashboard

However, when attempting to refresh the page by pressing F5, it results in an error message:

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

Any suggestions or solutions to prevent/issues of this nature related to CloudFront causing "Access Denied" errors when refreshing the page with the F5 key in Angular?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular: Using Observable.timer() and switchMap to delay function execution

This is how I approach the situation: filter(value) { this.backendCall(value) } To prevent my method from being called repeatedly for every keystroke, I aim to introduce a pause between backend requests using Observable.timer() and switch ...

How can I make CSS text-overflow ellipsis trigger a pop-up to display lengthy text when clicked?

I'm encountering an issue with a lengthy sentence in a table cell which I've truncated using text-overflow to display ellipsis. Is there a way to enable users to click on the dots (...) and view the full text in a popup window? table { wi ...

Tips for troubleshooting Angular 4 unit testing using jasmine and karma with simulated HTTP post requests

I have a service that I need to unit test in Angular 4 using TypeScript and Jasmine. The problem is with the http where it needs to perform a post request and get an identity in return, but for some reason, no data is being sent through. My goal is to ac ...

Upon transitioning from Angular 5 to Angular 6, a noticeable issue arises: The existing document lacks a required doctype

I recently updated my project from Angular 5 to Angular 6. Post-upgrade, everything compiles without errors. However, when I try to access the website, all I see is a blank screen. Upon inspecting the console, I came across the following error message: Th ...

Linking all styles with Angular 2

Is it possible to apply a style when the exact nature of that style is unknown? Consider a scenario where I have a model containing string variables defining styles, as shown below: myStyle1:string="margin-left:10px"; myStyle2:string="margin ...

What is the best way to retrieve specific data based on their unique identifier?

Imagine having a table like this, with the following data: Id , Name , IsBillable 1 One 1 2 two 0 3. three 0 I have stored this data in a variable called masterData using the get method, and I am using it to populate a dropdown me ...

Can the output object from an angular form validator be obtained and utilized?

As per the documentation, The validator is capable of returning an object {[key: string]: any} or null This implies that it can return an object (for any) which includes detailed information about what went wrong during validation. For example: function ...

What is the best way to output data to the console from an observable subscription?

I was working with a simple function that is part of a service and returns an observable containing an object: private someData; getDataStream(): Observable<any> { return Observable.of(this.someData); } I decided to subscribe to this funct ...

Angular 2 does not recognize the existence of .then in type void

I have a query regarding Angular2 and I'm struggling with the void function in my code. Can someone help me out? I am new to Angular2 and unsure of what needs to be added in the void function. Check out this image for reference export class PasswordR ...

Validate uniqueness of input in database using Angular's async validator

My <input> element allows users to enter a value that should be unique in the database. I'm looking for a way to validate this input dynamically on the front-end, and display an error message if the value is already in the database. ...

Unable to play audio src in Angular 2 due to http request issue

The data I gathered and included in the audio source is not playing. component.detail.ts export class DetailComponent implements OnInit { @Input() detailName: string; @Output("playnhac") play = new EventEmitter(); private mp3Link:string; ...

Oops! Issue: The mat-form-field is missing a MatFormFieldControl when referencing the API guide

I included the MatFormFieldModule in my code like so: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; ...

Newest Angular package.json

Each time I attempt to update my Angular components to the latest version, I encounter the same error. It seems like a never-ending cycle... npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/ ...

Using Angular CLI with ES6 instead of TypeScript for your development needs can offer a

Is there a way to utilize an ES6 transpiler such as Babel instead of TypeScript in an Angular CLI project? Are there any specific flags for specifying the script language, similar to using --style? Thank you. ...

The occurrence of a loading error arises when attempting to load the second component, displaying the message 'The template instructed for component SidebarComponent is

My journey with Angular has just begun, and I decided to challenge myself by creating a simplistic dashboard. In order to achieve this, I developed two components called DashboardComponent and SidebarComponent. The DashboardComponent loads smoothly witho ...

When attempting to open an Angular modal window that contains a Radio Button group, an error may occur with the message "ExpressionChanged

I am brand new to Angular and have been trying to grasp the concept of lifecycle hooks, but it seems like I'm missing something. In my current project, there is a Radio Button Group nested inside a modal window. This modal is triggered by a button cl ...

Utilizing models to establish the data type of an Observable within Angular

I have a simple query regarding a service. I have a method called getAllArticlesFromDb in my service that retrieves data from an API using an HTTP GET call. Here is the code for the method: article.service.ts getAllArticlesFromDb() : Observable<any> ...

Access-Control-Allow-Methods is not permitting the use of the DELETE method in the preflight response for Angular 2

I am having trouble deleting a record in mongodb using mongoose. Here is the code snippet from my component: deleteProduct(product){ this._confirmationService.confirm({ message: 'Are you sure you want to delete the item?', ...

Error message: "ExpressionChangedAfterItHasBeenCheckedError - encountered while using ngIf directive to hide/show a progress

My HTTP interceptor is set up to display a loading bar whenever an HTTP request is made: intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const dataStorageService = this.injector.get(DataStorageService); ...

Adjust the component suppliers based on the @input

If I were to implement a material datepicker with a selection strategy, I would refer to this example There are instances where the selection strategy should not be used. The challenge lies in setting the selection strategy conditionally when it is insta ...