After a successful login, Angular will once again redirect the user to the login page

I successfully implemented the back-end using nest-js to handle authentication with mongo-db. Registration and login are working fine, but I face an issue after logging in with a successful result - when I refresh the page, it redirects me back to the login route.

Here is the result of the cookie after successful login:

Authentication  
expires "2022-07-29T09:48:43.000Z"
httpOnly    true
path    "/"
value   "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2MmUyOTUzMmQwZGVmYjA5NGFiMTU0YzMiLCJpYXQiOjE2NTkwODQ1MjMsImV4cCI6MTY1OTA4ODEyM30.QfMS3hI-Jpyj9CCSPgQfxHplTewSX95rl7lLTVSm-pg"

And here is the POST response after login:

_id "62e29532d0defb094ab154c3"
email   "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e296879196a2858f838b8ecc818d8f">[email protected]</a>"

In my app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    NotFoundComponent,
  ],
  imports: [
    CommonModule,
    BrowserModule,
    GraphQLModule,
    HttpClientModule,
    HomeComponent,
    LoginModule,
    SignUpModule,
    AppRoutingModule,
  ],
  providers:
    [{
      provide: APOLLO_OPTIONS,
      useFactory: (httpLink: HttpLink) => {
        return {
          cache: new InMemoryCache(),
          link: httpLink.create({
            uri: '^api/graphql' //using proxy
          })
        }
      },
      deps:[HttpLink]
    }],
  bootstrap: [AppComponent]
})
export class AppModule {
}

For handling authentication, I have an auth.guard.ts

@Injectable({
  providedIn: 'root'
})

export class AuthGuard implements CanActivate {
  constructor(
    private readonly authService: AuthService,
    private readonly router: Router) {
  }

  canActivate() {
    return this.authService.isAuthenticated().pipe(
      tap((authenticated)=>{
        if(!authenticated){
          console.log('you should login')
          this.router.navigate(['login']);
        }
      })
    )
  }
}

Here is a snippet from my app.component.ts

@Component({
  selector: 'front-root',
  templateUrl: './front.component.html',
  styleUrls: ['./front.component.css']
})
export class FrontComponent implements OnInit {
  isLoggedIn$: Observable<boolean>;

  constructor(
    private readonly authService: AuthService,
    private readonly router: Router
  ) {
    this.isLoggedIn$ = authService.authenticated$;
  }

  ngOnInit(): void {
  }
}

And in my auth.service.ts

@Injectable({
  providedIn: 'root'
})

export class AuthService {
  private readonly authenticated = new Subject<boolean>();
  authenticated$ = this.authenticated.asObservable();

  constructor(private readonly httpClient: HttpClient) {}

  isAuthenticated() {
    return this.httpClient.get<boolean>('api/auth/login').pipe(
      tap(() => {
        this.authenticated.next(true);
      }),
      catchError(() => of(false)));
  }
}

When trying to access the teachers route, I get a 404 error with the message "you should login". This error module redirects me to the login page instead.

In my proxy.conf.json

{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false,
    "pathRewrite": {
      "^/api": ""
    },
    "logLevel": "debug"
  }
}

And in my angular.json

"configurations": {
  "production": {
    "browserTarget": "front-end:build:production" ,
    "proxyConfig": "src/proxy.conf.json"
  },
  "development": {
    "browserTarget": "front-end:build:development",
    "proxyConfig": "src/proxy.conf.json"
  }
},

Answer №1

After subscribing to your event/service and receiving the accurate data, it is crucial to store the token securely before utilizing the Router to navigate to a different page, a step that seems to be missing in your component.

Perhaps delving into the Angular documentation on routing can provide you with deeper insights on this matter:

https://angular.io/guide/router

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

What is the syntax for adjusting background-position with ngStyle in Angular 4?

It's finally Friday! I'm a bit confused about how to properly set the background-position-x property in an [ngStyle] directive in Angular 4 with Ionic 3. Can someone guide me on the correct way to implement background-position-x? I expect the ou ...

The popup is unable to remain in the center of the screen because the background page keeps scrolling back to the top

Whenever I click a button to open a popup window, the page unexpectedly scrolls to the top. It's frustrating because if I'm at the bottom of the page and press the 'submit' button, the popup doesn't display in the center as intende ...

Accessing data stored in XML or JSON files from a local server

I am currently working on loading a list of coordinates for a Google map from either an XML or JSON file, both of which are hosted in the same directory on my local test server. So far, I have used a hard-coded JSON object to load map coordinates for tes ...

Configuring Braintree Client with JS v3 - encountering a null payment_method_nonce causing issues with form submission

I have successfully integrated Braintree into my Laravel 5.2 app using JS v2 client setup, but now I want to upgrade to v3. I have customized the code from the docs as follows: <form id="checkout-form" action="/checkout" method="post"> <div id= ...

To add a span within a contenteditable field, restricting the user from inputting beyond the inserted span

When the user presses the space key, I want an auto input span to appear. However, when I trace them in the devtools, range.setEnd(lasttextnode, 0); and range.collapse() seem to work correctly. The issue arises when the keyboard input is not right. I try t ...

Embed the component into the array collection

I have an array and I want to display a random component inside it. Specifically, I want to include the FeedbackComponent before the last two objects in the array. This is how it should look like in a schematic representation: storyObject storyObject st ...

Tips for concealing select options after choosing with select picker?

Our establishment features three distinct rooms, each offering three identical options that users can choose from. https://i.sstatic.net/Jx4Me.png To illustrate, if a user named John selects option one in the first room, that same option will be hidden w ...

Guide on converting a date input to a timestamp

I am trying to convert the date retrieved from an HTML5 date input into a timestamp and store it as a variable. HTML: <form> <section class="input"> <input type="date" id="date" name="maintenanace_date"/> </section> <sectio ...

Why is my timer function speeding past too swiftly?

My vue.js countdown function is updating too quickly. Displayed below is the data section data() { return { selected: [], countdown: timerLimit } Here is the countdown method countdownTimer() { this.count ...

The functionalities of model() and output() in Angular 18 appear to be malfunctioning

I am encountering an issue in my Angular 18 application while trying to implement a ModelSignal. The compiler is throwing an error message stating Can't bind to test since it is not provided by any applicable directives. I have carefully reviewed the ...

Hiding or removing DOM elements with ng-bootstrap pagination

I am in the process of incorporating pagination into my project using ng-bootstrap pagination. In my HTML, I am combining an ngFor loop with the slice pipe to filter elements for display. <tr *ngFor="let bankAccount of bankingAccounts | slice: (p ...

Creating a dual-direction infinite scroll effect with CSS through mouse dragging

I'm currently working on implementing an infinite scroll component for a project. After consulting this tutorial, I've encountered an issue. It seems that I can only achieve infinite scroll in one direction. Whenever I add elements to the leftmo ...

How can I display an iframe element only if it exists within an object in Angular?

I'm currently exploring options to specifically display the iframe element within a block of HTML content being sent to my Angular application. While I can use a *ngIf directive in my template to check for the presence of the tag, I am unsure of how ...

Tidying up following the execution of an asynchronous function in useEffect

Recently, I've been facing a challenge while migrating a React project to TypeScript. Specifically, I'm having trouble with typing out a particular function and its corresponding useEffect. My understanding is that the registerListener function s ...

Having trouble updating Angular-Datatables in Angular 17: Issues with Re-rendering the DataTable

Currently immersed in the development of an Angular 17 application that utilizes Angular-Datatables. I am facing difficulties in re-rendering the DataTable upon updating data post a search operation. Delve into the snippet below, which showcases the pertin ...

Why does this asynchronous function initially return nothing, only to suddenly return all results on subsequent tries?

My current task involves inserting data into my database within a map loop. To ensure that the loop completes before proceeding, I am utilizing an async function to store all results in the variable "practicasAgregadas." This is how I invoke the function: ...

Accessing information from a database table using Highchart and Ruby on Rails (ROR

I have a Ruby on Rails application that utilizes highcharts. I am currently working on enhancing it to display the amount of time spent on specific projects. To demonstrate what I am trying to achieve, I have created a JSFiddle example which can be found h ...

Guide on positioning the camera to track the model in a third-person view

Currently, I am tackling a project in Three.js where I am in need of setting up a third-person camera that tracks a 3D model as it navigates through the scene. Despite having a basic framework with animations and controls, I am encountering difficulties in ...

The initial rendering of the NextJs 13 application is experiencing significant sluggishness when deployed on an EC2

After deploying my NextJS 13.4 app on an AWS EC2 instance with 2 GB of RAM, I noticed that the initial load time is quite slow, taking around 20 seconds to load for the first time. The development mode in NextJS builds and displays the result, which may co ...

Ways to minimize the occurrence of duplicate values in a table

In the application, I have a table where I add multiple values to an Array. These arrays display the values in the table columns, sometimes resulting in duplicate values. Below is a small example to illustrate the issue. What is the best way to eliminate ...