The user keeps finding themselves redirected back to the Home page rather than the page they are trying

Within my Angular application, users are authenticated through an OIDC provider using the library angular-auth-oidc-client. In the scenario where a user is not authenticated or their session has expired and they attempt to access a page such as https://localhost:4202/account, they are automatically redirected to the OIDC login page. However, upon successful login, the user is consistently redirected to the home page instead of the originally requested page.

To Reproduce:

Steps to reproduce this behavior:

  1. Update the Auth configuration with your own settings
  2. Launch the project by running:
npm run start
  1. Navigate to https://localhost:4202/account. After being redirected to the OIDC login page, complete the login process successfully. The user will be redirected to https://localhost:4202 instead of the intended https://localhost:4202/account page.

Answer №1

The main issue arose from neglecting to store the redirectedUrl in storage and then retrieving it after the successful navigation process. Fortunately, the library includes a helpful feature called AutoLoginPartialRoutesGuard, which can be utilized within custom guards. For further details, refer to the source code on Github and observe the example of an admin guard that extends AutoLoginPartialRoutesGuard. This implementation ensures that the user is redirected back to their original URL.

Admin Authentication Guard:


@Injectable({
    providedIn: 'root',
})
export class AdminUserAuthGuard implements CanActivate {
    constructor(
        private router: Router,
        private autoLoginPartialRoutesGuard: AutoLoginPartialRoutesGuard
    ) {}


    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        if (this.autoLoginPartialRoutesGuard.canActivate(route, state) && this.currentUserState.hasSysAdminRole) {
            return true;
        }
        if (this.autoLoginPartialRoutesGuard.canActivate(route, state) && !this.currentUserState.hasSysAdminRole) {
            this.router.navigate(['/unauthorized']);
        }
        return false;
    }
}

Answer №2

in authentication service:

this.authenticationService.loadDiscoveryDocAndLogIn().then(
        (isLoggedIn) => {

          if (isLoggedIn) {
            this.authenticationService.setupAutoSilentRefresh();
            resolveFunction();
          } else {
            this.authenticationService.initImplicitFlow(window.location.pathname);
            rejectFunction();
          }
        })

initialization code:

initializeLogin() {
   this.authenticationService.events
    .pipe(
      filter((e: any) => e.type === 'token_received'))
    .subscribe(({ type }) => {
      this.router.navigateByUrl(decodeURIComponent(this.authenticationService.state));
    });
 }

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

Having a problem with Angular 5 npm install due to a peer dependency issue

Our team is facing an issue with our Angular solution that runs smoothly on one machine, but throws errors when the 'npm install' command is executed on another machine... npm install The errors we are encountering are related to missing peer d ...

Setting the default theme in Material UI4

I am attempting to apply a default theme to the makeStyles function in material ui 4. Within my component, I have imported my theme from Styled Components and passed it to customMaterialStyles for makeStyles. The main component import { faTimes } from &a ...

Enhance Angular Material Select with Tooltip on Ellipsis Directive

In the midst of my Angular 9 project journey, I encountered a directive designed to add a matTooltip if an element's text is truncated (ending in ellipsis due to overflow). Everything was running smoothly with this directive until I introduced a mate ...

Found within the NgModule.imports of ViewClientModule, however, contains errors within the export class SharedModule { }

Recently, I upgraded my Angular project from version 11 to 13. After the upgrade, I encountered an error message "error NG6002: Appears in the NgModule.imports of VerifiedprofilesharedModule, but itself has errors 664 export class SharedModule { }" view i ...

Steps to converting an enum or literal

Hey there, I'm relatively new to working with TypeScript and I've been experimenting with transforming enums/literals using functions. For instance, creating a capitalize function that capitalizes the first letter of a string. (e.g., mapping typ ...

Dealing with "Cannot find name" errors in Typescript when working with React components

I'm currently in the process of transitioning my React code to TypeScript, and I've encountered numerous challenges. One recurring issue is the "Cannot find name" errors that pop up when converting my .js files to .ts files. Let's take a lo ...

Retrieve upcoming route details within canDeactivate guard in the updated Angular2 router

Is there a way to retrieve the upcoming route information within the "canDeactivate" guard of Angular 2's new router? ...

Reaching the maximum request threshold

Currently, I am facing an issue where users are able to upload files from the client side (using Angular 4) to the server (implemented with Spring Boot). The problem arises when a user attempts to upload more than 6 files at once. In such cases, Chrome uti ...

Check the status when clicking on an event using Angular Material

I am working with an Angular element that involves a checkbox. <mat-checkbox class="btn-block" labelPosition="before" (change)="showOptions($event)" (click)="makeJSON($event.checked,i,j,k)"> </mat-chec ...

Validation of passwords in reactive forms using Angular Material Design Lite

I have a password field with specific validation requirements: The password must be alphanumeric It cannot consist solely of characters or numbers <p> <mdl-textfield label="Password" ...

I am currently facing challenges retrieving data from a post request in my Angular/Typescript frontend application connected to an ASP.NET backend

I am currently working on a web application that relies on backend processing. To communicate between my Angular(v14)/Typescript front end and an ASP.NET backend, I am sending a post request. Backend Code [HttpPost] public async Task<string> Process ...

What is the method for incorporating sorting into a mat-list?

I've searched for various solutions, but none seem to work with mat-list. It's crucial for me because mat-list is the only solution where drag&drop functionality works (I always face this issue with mat-table in tables and I can't find a ...

Updating a null value within the database was done successfully

Currently, I am working with angular CLI version 8.1.0 and have a user list displayed on a mat table. Upon clicking on a specific user, a new page opens up containing two buttons - "approve" and "reject". The issue I am facing is that when I click on "ap ...

The Angular application has been successfully compiled, yet it is not loading in the browser. Additionally, an Uncaught ReferenceError is being thrown, stating that 'process

After updating my Angular application from version 11 to version 12, I spent a lot of time fixing errors and finally got the application to compile successfully. However, when I try to view it on the local server, nothing is appearing on the screen. There& ...

Error message: "Unable to emit an array with Angular

Within the DateRangeComponent, I am attempting to trigger an array emission to another component (ViewerComponent) upon button click using the EventEmitter and Output decorator. The DateRangeComponent contains a getData() method which utilizes the EventEm ...

Making a quick stop in Istanbul and NYC to collect a few important files

Setting up Istanbul/Nyc/Mocha for test coverage in my project has been a bit of a challenge. While I was successful in running Nyc, I noticed that not all the .ts files in my project were being picked up for test coverage. When I execute npm run coverag ...

Asynchronous and nested onSnapshot function in Firestore with await and async functionality

I'm facing an issue with the onSnapshot method. It seems to not await for the second onsnapshot call, resulting in an incorrect returned value. The users fetched in the second onsnapshot call are displayed later in the console log after the value has ...

Craft fresh items within HTTP request mapping

I am currently working on a function that subscribes to a search api. Within the map function, my goal is to transform items into objects. I haven't encountered any errors in my code, but the response always turns out empty. Here's the snippet o ...

Changing the ngModel value within ngFor loop

I am working on a project where I need to display a list of grades from an object called 'grades'. Additionally, I want to integrate a slider component for each grade, with the value of the slider corresponding to a predefined list. However, it s ...

How can I clear the div styling once the onDismiss handler has been triggered

Seeking assistance with resetting a div on a Modal after it has been closed. The issue I am facing with my pop-up is that the div retains the previous styling of display: none instead of reverting to display: flex. I have searched for a solution without su ...