Search code examples
keycloaksveltekitkeycloak-services

SvelteKit and keycloak-js, code_to_token_error and invalid_client_credentials error


I'm using keycloak-js to secure my sveltekit UI app.

<script lang="ts">
    import { onMount } from "svelte";
    import Keycloak from "keycloak-js";
    import type { KeycloakInitOptions }  from "keycloak-js";
    onMount(  () => {
        let instance = {
            url: "http://localhost:8080",
            realm: "my-realm",
            clientId: "my-client"
        };
        let keycloak = new Keycloak(instance);
        let initOptions: KeycloakInitOptions = { onLoad: "login-required" 
        };
        keycloak.init(initOptions).then(function (authenticated) {
                console.info("authorized);
            }).catch(function () {
                alert("unauthorized");
            });
        }
    );
</script>

I'm receiving this error on my keycloak deployed in docker.

WARN  [org.keycloak.events] (executor-thread-69) type=CODE_TO_TOKEN_ERROR, realmId=..., clientId=my-client, userId=null, ipAddress=..., error=invalid_client_credentials, grant_type=authorization_code

Retrieving the token from postman works though.


Solution

  • Based on your error message:

    WARN  [org.keycloak.events] (executor-thread-69) type=CODE_TO_TOKEN_ERROR, realmId=..., clientId=my-client, userId=null, ipAddress=..., error=invalid_client_credentials, grant_type=authorization_code
    

    it looks like Keycloak is expecting a client secret, which based on your configuration:

    let instance = {
        url: "http://localhost:8080",
        realm: "my-realm",
        clientId: "my-client"
    };
    

    infers that the client my-client is a confidential one. However, since you are using the javascript adapter, you should actually create a public client instead of a confidential one.

    So change the access-type of the client my-client from confidential to public.