3

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?

ochs.tobi
  • 3,214
  • 7
  • 31
  • 52

2 Answers2

3

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.

0

After more research I haven't found a solution to get the users information without an extra http call to the server.

The APP_INITIALIZR worked fine for my initial use-case. But later my AuthenticationService were expanding and the APP_INITIALIZR can't handle Services that need to inject the router due to cyclic dependency. Therefore I recommend the solution in the accepted answer.

ochs.tobi
  • 3,214
  • 7
  • 31
  • 52