I am able to login to Keycloak using the keycloak-js
client, however, when making a fetch
request, I get the following error:
JavaScript
x
2
1
Access to fetch at 'https://xxxxxxxx.com/auth/realms/app_testing/protocol/openid-connect/token' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
2
The post request I am making is
JavaScript
1
17
17
1
var formData = new FormData()
2
formData.append("client_id", 'vue_blog_gui');
3
formData.append("grant_type", "password");
4
formData.append("client_secret", "705669d0-xxxx-xxxx-xxxx-4f4e52e3196b");
5
formData.append("scope", "openid");
6
formData.append("username", "user@example.com")
7
formData.append("password", "123")
8
9
fetch(
10
'https://xxxxxxxx.com/auth/realms/app_testing/protocol/openid-connect/token',
11
{
12
method: 'POST',
13
'Content-Type': 'application/x-www-form-urlencoded',
14
data: formData
15
}
16
)
17
The keycloak settings are
- Root URL:
http://localhost:8080
- Valid Redirect URIs:
http://localhost:8080
- Base URL:
/
- Admin URL: Empty
- Web Origins:
*
// but I have also triedhttp://localhost:8080
and +
My app is running on http://localhost:8080
Advertisement
Answer
I managed to solve the problem. It was the format of the data I was sending to Keycloak. I need to URLEncode the FormData adding it to the body of the Fetch request. Also, was using data
rather than body
in the fetch request.
Anyway, I solved it by putting all the data into PostMan, getting it working in there and then taking the Auto Code generation that Postman provides to come up with this.
JavaScript
1
26
26
1
var myHeaders = new Headers();
2
myHeaders.append('Content-Type', 'application/x-www-form-urlencoded');
3
4
var urlencoded = new URLSearchParams();
5
urlencoded.append('client_id', 'vue_blog_gui');
6
urlencoded.append('username', 'me@example.com');
7
urlencoded.append('password', 'password');
8
urlencoded.append('grant_type', 'password');
9
urlencoded.append('scope', 'openid');
10
urlencoded.append('client_secret', '705669d0-xxxx-xxxx-xxxx-4f4e52e3196b');
11
12
var requestOptions = {
13
method: 'POST',
14
headers: myHeaders,
15
body: urlencoded,
16
redirect: 'follow',
17
};
18
19
fetch(
20
'https://keycloak.server.example.com/auth/realms/app_testing/protocol/openid-connect/token',
21
requestOptions
22
)
23
.then((response) => response.text())
24
.then((result) => console.log(result))
25
.catch((error) => console.log('error', error));
26