SpringCloud Dataflow Keycloak Angular 8 integration - 401 Unauthorized (sometimes(?))

457 Views Asked by At

I am working on a project with SpringBoot framework at backend and Angular8 at frontend. The connection between front and back is made with an nginx proxy server. I wanted to integrated with Keycloak and I used keycloak-angular v.6.1.0 library (https://www.npmjs.com/package/keycloak-angular) and keycloak-js v.9.0.3 (https://www.npmjs.com/package/keycloak-js) and at first sight seemed to be working smoothly. Concretely, the login page shows up, I provide the credentials, login succeeds and keycloak sends back the token which is used as an authorization bearer token for the requests that are sent to backend.

The problem that I am facing is that these requests usually succeed, but sometimes they don't, giving a 401 Unauthorized code. When I monitor these failed requests, I check the validity of the bearer token with jwt(https://jwt.io/) and it is always valid, and then I double-check with curl and the request succeeds and I get the expected results.

app.module.ts

export function initializer(keycloak: KeycloakService) {
  return async () => {
    const authenticated = await keycloak.init({
      config: environment.keycloakConfig
    });

    if (!authenticated) {
      console.log("Not authenticated")

      await keycloak.login({ scope: environment.scope });

      return authService.loadSecurityInfo(true)
        .pipe(
          map(securityInfo => {
            ....
          })
        ).toPromise();
    } else {
      console.log("Authenticated!")

      return authService.loadSecurityInfo(true)
        .pipe(
          map(securityInfo => {
            ...
          })
        ).toPromise();
    }
  };
}

I provide the code with the keycloak initializer and keycloak login. The loadSecurityInfo function just performs the get request in the respective endpoint at the backend.

LoadSecurityInfo

return this.http
  .get<any>(AuthService.URL.SECURITY_INFO, { headers: HttpUtils.getDefaultHttpHeaders() })
  .pipe(
    map(body => {
      ...
    })
  );

I was wondering if someone faces the same or similar problem and could give me some insights about what is maybe wrong. Thanks in advance! :D

0

There are 0 best solutions below