Search code examples
angularkerberosangular-route-guards

Angular get data from kerberos authentication


I have an angular application with a backend. The authentication is managed by the browser with Kerberos before the app has started. The response contains a JWT with roles in it.

My approach is an extra HTTP call to the server when the app is starting to get the users credentials. This is realized with the APP_INITIALIZER in app.module.ts, so I already have the credentials when the app has started.

providers: [
    ...,
    {
      provide: APP_INITIALIZER,
      useFactory: Utilitys.authServiceFactory,
      deps: [AuthenticationService],
      multi: true   
    }]

This is working fine. But my question is: Do I have to make an extra call or is there a way to get the response from the browsers request?

If yes: How is it possible?

If no: Is the APP_INITIALIZER a recommended way to fetch the data only once? Or should I protect all routes with a route guard that does the HTTP call?


Solution

  • To get data only once your application has started, you could do this also with Route Guards.

    You could define a componentless route that is protected by a route guard like this:

    // Route Guard
    canActivate(): boolean | Promise<boolean> | Observable<boolean> {
        if (this.yourService.isAuthenticated()) {
          return true;
        }
        return this.loginService.login();
    }
    
    // Routes
    {
        path: '',
        canActivate: [AuthGuard],
        children: [
          { path: 'comp1', component: Comp1 },
          { path: 'comp2', component: Comp2 },
          ...
        ]
    }
    

    This way every route is protected by your guard and you can check if your user is logged in / authenticated to access your application.

    Note that your regular components would be children of the componentless protected route.