Navigate to the Authorization Endpoint upon Initial Angular Load

Is there a way to redirect to the authorization endpoint before loading the Angular components and HTML? Can I use the CanActivate auth guard on my main app component for this purpose?

I have implemented an auth guard in my Angular project, but it seems to load the HTML before redirecting to the authorization endpoint.

This is what I have configured:

(Routing Component)

const routes: Routes = [
{
    path: '',
    redirectTo: 'main',
    pathMatch: 'full',
    canActivate: [AdminRouteGuard]
},
{
    path: 'main',
    component: MainComponent,
    canActivate: [AdminRouteGuard]
},
{
    path: '**',
    redirectTo: 'main',
    pathMatch: 'full',
    canActivate: [AdminRouteGuard]
}];

(Route Guard)

 export class AdminRouteGuard implements CanActivate {
  constructor(@Inject(DOCUMENT) private document: any, private _authService: AuthService, private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    if (this._authService.isLoggedIn()) {
      return true;
    }
    
    else {
      return this._authService.login();
    }}}

Answer №1

To achieve this, you can leverage the APP_INITIALIZER provider along with Auth Guards for a more robust solution. Without knowing your specific identity management setup, I'll outline a general approach to creating your initializer.

function authInit(authService: AuthService) {
  return () => {
    // Add authentication logic here and return a Promise
    // Implementation will vary based on your service or IM solution
  })
}

@NgModule({
  declarations: [AppComponent],
  imports: [AppRoutingModule, BrowserModule],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: authInit,
      multi: true,
      deps: [AuthService],
    },
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

The custom factory function authInit returns a function that should resolve a Promise. This way, initialization will wait until the Promise is resolved before proceeding. Give it a try!

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

tips for choosing an entire group in ng-select with Angular

I am implementing a multi-select dropdown with groups in Angular using the ng-select component. My goal is to allow users to select an entire group and have all items within that group automatically selected as well. I have been attempting to model my cod ...

What is the correct way to make a GET request with parameters included?

In order to retrieve data from an API using a declarative approach, you can define it in the service like this: getItems$ = this.httpClient.get<Item[]>(this.url); You can then either subscribe to it or use async in the consuming component. If the A ...

Guide to troubleshooting a Typescript NodeJS application in a local Docker container using VScode

Below is my Dockerfile: FROM node:20-alpine WORKDIR /var/www/ COPY package*.json ./ RUN npm install COPY . . EXPOSE 80 EXPOSE 5858 # Run the application CMD [ "npm", "run debug" ] This excerpt shows the relevant part of my packag ...

Issue: Unable to find solutions for all parameters in (?, ?)

Below is the unit test I've written for my Angular 10 component, which showcases a tree view with interactive features: import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/for ...

Is there possibly a problem with GridActionsCellItem and its props?

I'm encountering a problem with passing props into the GridActionsCellItem within the '@mui/x-data-grid'; columns; { field: 'actions', type: 'actions', width: 80, getActions: (params: any) =&g ...

Enhancing Material UI v4 Themes using TypeScript

I am attempting to implement my own custom palette option in the theme section, but I am struggling with how to do the augmentation part using TypeScript. So far, I have created a file named "material-ui.d.ts" and inside it, I only have: import { PaletteO ...

Executing npm and ng commands via an Ant script on a Windows machine leads to the error message "The specified file could not be found."

When attempting to execute the following Ant script, which runs the "npm" command: <target name ="test"> <exec executable="npm" failonerror="true"> <arg value="install" /> </exec> </target> An error occurs, i ...

transmit information from the current state to a fresh task within an rxjs effect

My goal is to access state data and use it as properties for a new action. I successfully extracted the necessary data from the state after triggering the effect, but I am facing an issue when dispatching the new action with the data. It seems that I am un ...

There was an error linking the module "electron_common_features" which caused the Electron react test to fail

I recently developed a React Electron application using the electron-react-boilerplate template. I also added the @electron/remote package and made changes to the test case. However, upon running the command npm test, an error message stating No such modul ...

Maintaining accurate type-hinting with Typescript's external modules

Before I ask my question, I want to mention that I am utilizing Intellij IDEA. In reference to this inquiry: How do you prevent naming conflicts when external typescript modules do not have a module name? Imagine I have two Rectangle classes in different ...

Choosing Angular.json setups while executing a Docker multi-stage construction

I am currently in the process of developing an Angular6 application with a Docker multistage build. The default angular.json file generated by angular.cli includes a build section containing various configurations. To choose a specific configuration, I can ...

Encountering TypeScript error TS2345 while attempting to reject a Promise with an error

I recently encountered a perplexing TypeScript error message that I am struggling to comprehend. The specific error reads as follows: error TS2345: Argument of type '(error: Error) => void | Promise' is not assignable to parameter of type & ...

Unable to initialize default values on Form Load in Angular Reactive Forms

My goal is to make an HTTP request by passing an ID, then take the response and assign the values to form fields. I attempted using setValue and patchValue methods, but they did not yield the desired results. spService itemData = new ItemData() getIte ...

Exploring the Module System of TypeScript

I am working with a TypeScript module structured like this: let function test(){ //... } export default test; My goal is for tsc to compile it in the following way: let function test(){ //... } module.exports = test; However, upon compilation, ...

The width of Kendo Angular 2 grids pager and top header does not increase when scrolling

Our grids now have the horizontal scrolling feature enabled through CSS (kendo-grid {overflow: auto;}). However, we've noticed that the pager and top header of the grids do not expand their width when scrolling. Take a look at the screenshot below: ...

Save the chosen information into the database

My goal is to insert a Foreign key, acc_id, into the patient_info table from the account_info table. I have successfully retrieved the data from my database and now I want to use it as a Foreign key in another table. Here is the code snippet: try { $ ...

How can I prevent other input fields from being enabled once the value "matched" is received in the first input field using Angular?

When working with a template driven form, I encountered a scenario where I needed to disable other input fields if the value entered matched a specific string. For example, if the first input field's value is "sample", then the other input field shoul ...

Ionic 4: Facing issues with setting complete background image on ion-card

https://i.stack.imgur.com/3lH6h.png I'm currently attempting to set a background image for an Ion-card in order to completely cover the card's area. However, I'm facing an issue where the background image does not cover the entire area and ...

Angular data binding with [object object]

Upon receiving data from my API, the console displays the following structure: [ { id:"123", name:"asd", address:"st.dddss", status:1 } ] After attempting to iterate through it using ngFor, an error is thrown: E ...

Every time a new message is sent or received, I am automatically brought back to the top of the screen on the

I'm currently working on integrating a chat feature into my Angular Firestore and Firebase app. Everything seems to be functioning well, except for one issue - whenever a new message is sent or received, the screen automatically scrolls up and gets st ...