sunmingtao / sample-code

3 stars 4 forks source link

Cannot send Ajax request to Keycloak: CORS header ‘Access-Control-Allow-Origin’ missing #225

Closed sunmingtao closed 3 years ago

sunmingtao commented 3 years ago

jQuery code:

$.ajax({
    url: "http://localhost:8080/auth/realms/trove/protocol/openid-connect/auth?client_id=trove&response_type=code&login=true&redirect_uri=http://localhost:8081/authcallback",
    cache: false,
    xhrFields: {
        withCredentials: true
    },
    crossDomain: true
});

Corresponding request:

Host: localhost:8080
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:83.0) Gecko/20100101 Firefox/83.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://localhost:8081
Connection: keep-alive
Referer: http://localhost:8081/
Cookie: AUTH_SESSION_ID=aaecac03-0a64-4bd7-877c-e6bea2e47f7a.pc202234; ......
sunmingtao commented 3 years ago

Change the request to jsonp solves the problem

$.ajax({
    url: "http://localhost:8080/auth/realms/trove/protocol/openid-connect/auth?client_id=trove&response_type=code&login=true&redirect_uri=http://localhost:8081/authcallback",
    dataType: "jsonp"
});

Corresponding request:

Host: localhost:8080
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:83.0) Gecko/20100101 Firefox/83.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Referer: http://localhost:8081/
Cookie: AUTH_SESSION_ID=aaecac03-0a64-4bd7-877c-e6bea2e47f7a.pc202234; 

The only difference is the removal of Origin header

Note: jsonp only support GET method.

sunmingtao commented 3 years ago

the /auth path of Keycloak always rejects cross domain ajax requests even if the 'Web Origins' has * in it