Keycloak encounters a CORS Access-Control-Allow-Origin issue

After successfully logging into Keycloak using the keycloak-js client, I encountered an error when attempting to make a fetch request. The error message received was:

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.

The post request being made is as follows:

var formData = new FormData()
formData.append("client_id", 'vue_blog_gui');
formData.append("grant_type", "password");
formData.append("client_secret", "705669d0-xxxx-xxxx-xxxx-4f4e52e3196b");
formData.append("scope", "openid");
formData.append("username", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ea9f998f98aa8f928b879a868fc4898587">[email protected]</a>")
formData.append("password", "123")

fetch(
  'https://xxxxxxxx.com/auth/realms/app_testing/protocol/openid-connect/token',
  {
    method: 'POST',
    'Content-Type': 'application/x-www-form-urlencoded',
    data: formData
  }
)

The Keycloak settings are as follows:

  • Root URL: http://localhost:8080
  • Valid Redirect URIs: http://localhost:8080
  • Base URL: /
  • Admin URL: Empty
  • Web Origins: * // but also tried http://localhost:8080 and +

My application is currently running on http://localhost:8080

Answer №1

After some troubleshooting, I successfully figured out the issue. It turns out that the problem lied in the data format being sent to Keycloak. I needed to URLEncode the FormData and add it to the body of the Fetch request, instead of using data as I was doing previously.

To resolve this, I decided to input all the data into PostMan, where I managed to get it working correctly. Using the Auto Code generation feature provided by Postman, I was able to come up with the following solution:

var myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/x-www-form-urlencoded');

var urlencoded = new URLSearchParams();
urlencoded.append('client_id', 'vue_blog_gui');
urlencoded.append('username', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bdd0d8fdd8c5dcd0cdd1d893ded2d0">[email protected]</a>');
urlencoded.append('password', 'password');
urlencoded.append('grant_type', 'password');
urlencoded.append('scope', 'openid');
urlencoded.append('client_secret', '705669d0-xxxx-xxxx-xxxx-4f4e52e3196b');

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: urlencoded,
  redirect: 'follow',
};

fetch(
  'https://keycloak.server.example.com/auth/realms/app_testing/protocol/openid-connect/token',
  requestOptions
)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log('error', error));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Challenges with integrating PHP and JavaScript technologies

I am currently facing a challenge with transferring data from a PHP file to Javascript. I have set up a PHP file to pull data from a database and display it in HTML. My goal is to load this data when the page loads, store it in JavaScript arrays, and acc ...

Using Next.js to pass data as an object in a getStaticProps function

Recently, I have started delving into the world of typescript and next.js. My current project involves deploying a Next.js web application on Vercel, which will be fetching data from a Heroku PostgreSQL database using Prisma. My goal is to display this dat ...

Seamlessly Loading Comments onto the Page without Any Need for Refresh

I am new to JavaScript and I am trying to understand how to add comments to posts dynamically without needing to refresh the page. So far, I have been successful in implementing a Like button using JS by following online tutorials. However, I need some gui ...

Checking a bcrypt-encrypted password in an Express application

I am encountering an issue with my login password verification code. Even when the correct password is entered, it is not being validated properly. Can anyone provide assistance with this problem? login(req, res) { const { email, pass } = req.body; ...

Preserving variable scope in JavaScript even after defining a function

I am facing an issue with my JavaScript code that involves invoking a function within a function: var obj = { // returns the function with prevent default prepended. run: function(functor, context){ return function(e){ e.preventDefault(); ...

JavaScript Error: Unable to determine the value of a null property

Is there a way to validate the user's input in real-time on an HTML form? Take a look at the following HTML code: <div class="col-md-2"> <input class="form-control" name="nbequipement" id="nbequipement" placeholder="" type="text"> ...

Is jQuery.each() failing to function properly in Firefox and Internet Explorer?

Having trouble with the $.each function behaving differently across browsers. I have lists with background images, and I want the parent div to fade in once these images finish loading. My code seems correct as there are no JavaScript errors in the conso ...

Struggling to display Firebase Auth information resulting in 'undefined' value within React web application

When loading a user's profile page, I am trying to display their displayName and email information retrieved from Firebase Auth. I have implemented this logic within the 'componentDidMount' method by updating the state with the response dat ...

Is it possible to submit two forms simultaneously using jQuery or AJAX?

My plan is to save 2 forms, with the first form providing the Foreign key for the second form. This is my attempt at saving this using JavaScript: $("#btnSave").click(function (e) { e.preventDefault(); $('#workForm').submit(); ...

Thymeleaf: Expression parsing error

I am working on a Thymeleaf template that includes pagination functionality. <ul class="results_perpage" > <li th:if="${previous != null}"><a th:href="javascript:movePage(`${previous}`);" class="results_menu" th:text="PREVIOUS">< ...

Are your Express routes failing to function properly?

I recently embarked on creating a new Express app by following the tutorial from Code Magazine. Below are my app and the defined route for /img. https://i.sstatic.net/G6PUG.png Upon trying to access http://localhost:3000/img or http://localhost:3000/img/ ...

Ajax- priorToSend

To avoid encountering the same error twice, I implemented the use of beforeSend in my code. hasSent = false function submit() { if (!hasSent) { $.ajax({ url: "${createLink(controller:'userInvitation', action:'ajaxUp ...

Using Angularjs and PHP: incorporating URL parameters into the $http.get() function

I am currently working on a web project in Eclipse with three main files: "controller.js", "home.html," and "array.php". The goal is for the .php file to echo a PHP array encoded in a JSON string: <?php $arr = array(array(title => "hello", auth ...

Receiving a response from a Node.js server using an AJAX GET request

Here's a snippet of code from app.js that retrieves an aggregated value from mongo.db. I'm attempting to use this response value on my HTML page by making an AJAX call. However, I'm facing an issue where I can't retrieve the value in my ...

Enhance your Laravel project with the powerful autocomplete functionality of Devbridge jQuery Autocomplete

I'm facing an issue while attempting to implement an AJAX search with jQuery autocomplete that isn't functioning as expected. Here's what my controller looks like: $search_term = Input::get('search'); $search = Topic::select(&apo ...

The Twitter widget functions properly upon initial loading, but subsequently malfunctions

I have a web application built using the Play Framework that utilizes Ajax to load view html pages into a 'container' div. $( "#container" ).load("/contactUs"); // The contactUs page contains the widget In one of my html pages, I include a Twit ...

JavaScript callbacks using customized parameters

I am currently grappling with the challenge of incorporating an asynchronous callback in node without prior knowledge of the potential arguments. To provide more clarity, let me outline the synchronous version of my objective. function isAuthorized(userI ...

React doesn't have file upload configured to update the state

I am working on integrating a file upload button that sends data to an API. To ensure only the button triggers the upload dialog and not the input field, I have set it up this way. Issue: The File is not being saved to state, preventing me from using a ...

Concealing two div elements based on string content

I am working on a unique Wordpress blog post layout that showcases personnel profile cards, displaying 12 individuals at a time. Depending on whether or not a person has a Twitter handle entered in the backend, certain elements should either be shown or hi ...

Modify JointJS/Rappid inspector or cell model value without relying on the inspector

Recently, I've encountered a challenge in updating the value of a text attribute (name) in a cell model without resorting to the use of the inspector. My goal is for this update to not only reflect in the inspector field but also in the linked cell mo ...