I configured keycloak with ExpressJS and would like to check if everything is working correctly. For this, I created these two scripts. One is an axios script to send the request to the server, and the other is a server side script. script to handle the request. But it doesn’t redirect me to the keycloak login page as I expected. I got an error instead
Here are some screenshots:
THANKS YOU
below is the script i use to send request
const PORT = 3001
const HOST = `http://localhost:${PORT}`;
/**
* This function aim is to log the user in
* @param user the user username
* @param pwd the user password
**/
export function loginRequest(user, pwd,) {
axios.post(`${HOST}/ `, {
email: `${user}`,
pwd: `${pwd}`
})
.then(function (res) {
return res.data
})
.catch(function(err) {
console.log('ERROR while sending login request :', err);
})
return false;
}
There is my front-ent where am getting the error. i just use the button to send request on click
and
There is my keycloak configuration
i trying a lot of thing found on internet like adding + in web origin field, but did not work.
2
Answers
I finally have the solution. I was trying to get redirected to the keycloak login page by clicking a button. I found out that I had to use the keycloak-js library to manage keycloak on my front-end. So the following code helped me.
Check documentation
It isn’t "axios" that throws the CORS error, it is your browser.
CORS is a browser-side security construct. When your browser goes to make a "fetch" or "axios" call, it first sends an OPTIONS request to the URL that it will eventually make a GET/POST/PUT/… request for.
The browser looks at the response headers from the OPTIONS request. That is how the server tells the browser "it is safe to make a fetch from the following sites: ….." — in other words, "it is safe to call this server’s APIs from web pages that are coming from the following sites: …..". This mechanism is how a server is able to tell the browser which sites/pages are safe to call the APIs from.
For example, a bank’s server would indicate that it is only safe to call the APIs from the bank’s website (https://mybank.com). Anyone putting up a web page at some other address (e.g. https://myfakebank.com) could put calls to the bank’s API server, but the browser would throw a CORS error because the fake webpage would not be served from a "valid" site.
So in your case, look at the headers of the RESPONSE to the OPTIONS call in your browser’s NETWORK tab of the Dev Tools and see if it is giving the appropriate response (i.e.
Access-Control-Allow-Origin: *
orAccess-Control-Allow-Origin: http://localhost:3000
). If not, then your browser will not allow you to make the call tohttp://localhost:3001
.There also seems to be some weird proxying going on in your configuration as the call to
http://localhost:3001
is being directed tohttp://localhost:8080
????