3
votes

I'm trying to login using keycloak from existing login page in localhost (localhost:3000). Keycloak run on another host (http://kchost:38080). I know it's not the recommended way to login but I need to adapt an existing system in no time.

Trying with curl:

    curl --location --request POST 'http://kchost:38080/auth/realms/myrealm/protocol/openid-connect/token' \
        --header 'Content-Type: application/x-www-form-urlencoded' \
        --data-urlencode 'client_id=publictestclient' \
        --data-urlencode 'username=myuser' \
        --data-urlencode 'password=mypass' \
        --data-urlencode 'grant_type=password'

I successfully get the expected response (with access_token and refresh_token). I'm not able to do the same on browser. The error is related to CORS.

I'm using axios and here is the code:

axios.defaults.httpsAgent = new https.Agent({ rejectUnauthorized: false })
axios.defaults.crossDomain = true;

await axios({
            method: "POST",
            url: 'http://kchost:38080/auth/realms/myrealm/protocol/openid-connect/token',
            headers: {
               "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
               'Access-Control-Allow-Origin': '*'
            },
            data: {
               client_id: 'publictestclient', 
               username: 'myuser', 
               password: 'mypass', 
               grant_type: 'password', 
           }
})

The error is: Access to XMLHttpRequest at 'http://kchost:38080/auth/realms/myrealm/protocol/openid-connect/token' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

If I omit the header 'Access-Control-Allow-Origin': '*', the error becomes: Access to XMLHttpRequest at 'http://kchost:38080/auth/realms/myrealm/protocol/openid-connect/token' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

On Keycloak admin side the client has access type 'public' in order to avoid 'clientSecret' requirement. Direct Access Grants Enabled is enabled. Tried different configuration for 'web origins' and 'valid redirect url', the current one is:

valid redirect url: localhost*
web origins: *

I'm pretty sure this is a problem related to server configuration. How can I solve?

1
Did you ever find a solution to this? I'm having the same issueMLyck

1 Answers

1
votes

The valid redirect url should have http or https in front. So a valid for localhost could be: https://localhost/* The web origins should be something like https://localhost if you want to make it secure.