Search code examples
javawebhttp-redirectserverkeycloak

Keycloak redirects localhost and not redirect remote url


I have my Keycloak server and my web app connected with to Keycloak to do the login into the app.

If I run in local, its redirects perfectly, but if I deploy the server and the web app in the same server, when the web app redirects to keycloak it redirects to localhost not to the remote url.

Any idea how to avoid redirects to localhost?


Solution

  • Finally I found an answer that fits better in my case. I created a KeycloakConfigResolver class, where I load a KeycloakDeployment depending on the host of the machine where is running, like that it redirects perfectly to the desired host.

    @Configuration
    public class PathServerKeycloakConfigResolver implements KeycloakConfigResolver
    {
      @Override
      public KeycloakDeployment resolve(Request request)
      {
        String hostname = "Unknown";
    
        try
        {
          InetAddress addr;
          addr = InetAddress.getLocalHost();
          hostname = addr.getHostName();
          return KeycloakDeploymentBuilder.build(getKeycloakJson(hostname));
        }
        catch (IOException e)
        {
          e.printStackTrace();
          return null;
        }
      }
    
      private InputStream getKeycloakJson(String hostname) throws IOException
      {
        InputStream inputStream = new FileInputStream("src/main/resources/keycloak.json");
        InputStreamReader isReader = new InputStreamReader(inputStream);
        BufferedReader reader = new BufferedReader(isReader);
        StringBuffer sb = new StringBuffer();
        String str;
        while ((str = reader.readLine()) != null)
        {
          sb.append(str);
        }
    
        return new ByteArrayInputStream(sb.toString().replace("{param_keycloak_server}", hostname).getBytes(StandardCharsets.UTF_8));
      }
    
    
    }
    

    Where the keycloak.json is,

    {
      "realm": "FocusocKeycloak",
      "auth-server-url": "http://{param_keycloak_server}:8080/auth",
      "ssl-required": "external",
      "resource": "login-app",
      "verify-token-audience": true,
      "credentials": {
        "secret": "XXX"
      },
      "confidential-port": 0,
      "policy-enforcer": {}
    }