0

I am trying to find a solution that will redirect to the authorization endpoint before loading the angular first (html and components). Is that even possible? Or is it possible to use CanActivate auth guard on my main app.component?

I am using an auth guard, just like any other angular projects. But it first loads the html first before redirecting to the authorization endpoint.

Here's what I've done so far :

(My 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]
}];

(My 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();
    }}}
interkey
  • 355
  • 5
  • 21

1 Answers1

0

It is possible, you should utilize APP_INITIALIZER provider for that. And then in order to make it more robust combine it with Auth Guards. Since you didn't state what identity management solution you are using I'm providing a general way how to do create your own initializer.

function authInit(authService: AuthService) {
  return () => {
    // Do the authentication here and return Promise
    // Code here depends on your service and/or on your IM solution
  })
}

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

Your own factory function authInit returns function and if that function returns a Promise, initialization does not complete until the Promise is resolved. This should do the trick.

mat.hudak
  • 2,803
  • 2
  • 24
  • 39