amara amara - 3 months ago 49
reST (reStructuredText) Question

Generate token with Keycloak

I need to call a method of rest web services that requires authentication.
I have one json file keycloak.json and another comonApi.json file to generate the client with plugin Swagger.

But I do not know what to do with the other file keyclooak.json.

Please how I can generate a token with keycloak.json file for calling methods?

Answer

Solution for my question :

import org.keycloak.admin.client.Keycloak;

import org.keycloak.representations.AccessTokenResponse;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;

@Component

public class KeycloakUtils {

   @Value("${toto.realm}")
   private String realm;

   @Value("${toto.client.id}")
   private String clientId;

   @Value("${toto.server.url}")
   private String serverUrl;

   @Value("${toto.user.name}")
   private String userName;

   @Value("${toto.password}")
   private String password;

   @Value("${toto.client.secret}")
   private String clientSecret;

   private Keycloak keycloak;


   public Keycloak getInstance() {
         if (keycloak == null) {
                keycloak = Keycloak.getInstance(serverUrl, realm, userName, password, clientId, clientSecret);
         }
         return keycloak;
   }


   public AccessTokenResponse getAccessToken() {
         return getInstance().tokenManager().grantToken();
   }