Search code examples
javaspring-securitysingle-sign-onkeycloakspring-security-oauth2

Spring OAuth2 automatical login with Keycloak


I am not well experienced in Spring Security so my questions may sound a little weird.

My environment consists of 4 parts:

  • Keycloak authorization server (authorization server)
  • Spring resource server application (resource server)
  • 2 OAuth2 client applications (clients)

I configured well everything, the OAuth2 and SSO work fine with all of the applications.

Besides the OAuth2 configuration, there is more to do. When my user uses the client application, he will provide his credentials on a form when trying to access the resource. But my model (for the resource) is more complex, and I have to do some background (housekeeping) tasks from time to time. These tasks are not done by the user(in the name of the user) but requested by the client application itself. My question is, how to access the resource server's endpoint from my clients in the name of the client application itself.

My first thought is that the client application should store a long-term JWT token and use this token during the calls. But I am not sure about it. I don't want to waste time on bad paths that's why I am asking in the first place.

The crucial and most doubtful parts for me:

  • How to get a long term JWT from Keycloak
  • How to automatically login a background call (via SSO and OAuth2)
  • How to store the credentials for the automatic login.

Thank you for your ideas or advice.


Solution

  • You should never have long term tokens, because that is a security risk.

    If someone manages to get hold of a long term token, they then have long time to use it maliciously.

    I can't guide you how to set this up in keycloak etc. But i would use the Client Credential Flow to authenticate the server, and get a token each time one of these "housekeeping jobs" needs to be made.

    You can read more about the flow here Client Credential Flow