Secure authentication with Keycloak API

In my HTML page with JavaScript, I am trying to implement auto-login functionality for the user. Below is the code I have written:

var url = "http://localhost:8180/auth/realms/Myrealm/protocol/openid-connect/token";

const response = await fetch(url, {
    mode: 'no-cors',
    method: "POST",
    body: JSON.stringify({
        "client_id":"myclientid",
        "username":"admin",
        "password":"123",
        "grant_type":"password"
    }),
    headers:{
        "Content-Type": "application/json"
    }
})

In the Keycloak server, I have added Web Origins '*'. However, I am encountering the following error:

POST http://localhost:8180/auth/realms/Myrealm/protocol/openid-connect/token 400 (Bad Request)

I am unsure why it is not working as expected. Interestingly, when I use the terminal, it functions correctly:

curl -i -d "client_id=myclientid" -d "username=admin" -d "password=123" -d "grant_type=password" http://localhost:8180/auth/realms/Myrealm/protocol/openid-connect/token

(Keycloak version 4.8.3)


Update

const response = await fetch(url, {
    method: "POST",
    body: 'client_id=myclientid&password=123&username=admin&grant_type=password',
    headers:{
        "Content-type":"application/x-www-form-urlencoded"
    }
})

Upon making the above update, I received the following response:

https://i.sstatic.net/XG3xC.png

Answer №1

Finally got it to work! The issue was with sending JSON instead of using

application/x-www-form-urlencoded
and receiving a ReadableStream instead of a string in the response. Here is the updated code:

    const response = await fetch(url, {
        method: "POST",
        body: "client_id=myclientid&password=123&username=admin&grant_type=password",
        headers:{
            "Content-type":"application/x-www-form-urlencoded"
        }
      });
    response.body.getReader().read().then(function (data){
        var string = new TextDecoder("utf-8").decode(data.value);
        console.log(string);
    });

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

Utilizing JSON data for efficient React component rendering

As a newcomer to React, I am currently in the process of constructing a dashboard that showcases data from three different sensors. The information regarding these sensors is stored in a single JSON file where each sensor has its own ID and name. This JSON ...

PHP query Ajax navigation

UPDATED I have made progress with processing both menus in "process.php" and displaying the queries in index.php. process.php <?php $menu1 = $_POST["menu1"]; $menu2 = $_POST["menu2"]; if($menu1 == 0) { $sql = "SELECT * FROM Language WHERE ID = " ...

Encountering an issue while trying to initiate a fresh React Native Project

As I work through the setup steps outlined in the React Native Documentation on my M1 MacBook Pro, I encounter a stumbling block. Despite successfully running React projects and Expo projects on this machine before, I hit a snag when trying to create a new ...

What causes the non-reachable part of the ternary operator to be evaluated prior to updating the state with setTimeout?

Check out my latest code snippet for a react component that renders a massive component. While the huge component is still rendering, a loading indicator will be displayed. import * as React from "react"; import ReactDOM from "react-dom"; import {HUGECom ...

Using a node module for Three.js path manipulation

Currently, I am in the process of learning Three.js and have set up a basic project that runs on a node.js server while importing Three.js as a node module. Although my setup is working fine, I find myself a little bit confused about whether this is consi ...

Invoking a React function repeatedly (every second)

Currently, I am working with React and utilizing Material UI to create a modal. The modal is rendered as part of the body of the code, placed at the bottom of the page. Its visibility is controlled by the state; if it's open or closed. However, I&apos ...

The display of website content across various screens

I'm relatively new to creating websites using scripts, CSS, etc. But I feel like I'm getting the hang of it pretty well... Now I've reached a point where I want my site to look good on different screen resolutions. Currently, I have somethin ...

Browser tries to interpret Javascript code as a file organization system

Encountering an issue while trying to load my website. When I open index.html in my browser, I receive a problem loading page message. This response is puzzling as it does not indicate a file loading error. Here's a snippet of the response: Firefox c ...

Clicking on the icon reveals the current date

I need some help with the input field that displays the calendar date. Currently, I can only click on the input field to show the calendar date. What I actually want is for users to be able to click on a calendar icon to display the calendar date, which sh ...

Tips on avoiding quotation marks in a Less variable containing a color identifier

I'm currently working on an HTML/CSS project where I aim to establish classes for labels and texts based on their color. For instance: .text-red{ color: red; } .label-white{ color: white; } In order to achieve this, my approach involves cr ...

When using Angularjs and UIRouter, calling event.preventDefault() will prevent the default browser behavior and

A custom JavaScript prompt is triggered when a user clicks the back button on their browser by monitoring the $stateChangeStart event. Let's explore this scenario: Imagine users moving through pages 1, 2, and finally reaching page 3. Upon trying to g ...

"Is there a way to adjust the range slider to display currency instead of

I stumbled upon this amazing slider on codepen. Can someone guide me on how to adjust it to display a range from €500 to €6000 while keeping the vibrant red background? I've attempted various solutions like: <input id = "range" type = "range ...

Is it possible to retrieve the createdAt timestamp without displaying the 'GMT+0000 (Coordinated Universal Time)'?

After conducting an extensive search, I have yet to find a satisfactory answer. My goal is to configure it without including the CUT time. {name: "Registered:", value: `${user.createdAt}`}, {name: "Joined:", value: `${message.guild.joinedAt}`} Presently, ...

Utilizing Ajax to retrieve an array of input textboxes and showcase the outcome within a div container

This is the form that I have designed for displaying information: <form name='foodlist' action='checkout' method='POST'> <table> <tr> <td>Product Name</td> <td>Price</t ...

Loop through two sets of data and perform multiplication on specific attributes when they match

I have a unique item that looks like this Object {SD00002:1,SD00011:3,SD00002:6} The values of the properties are set automatically. Currently, I have an array of similar objects as shown in the image below: https://i.sstatic.net/pSkvf.jpg My goal is to ...

How to prevent v-menu from overlapping a navbar in Vue.js

Exploring the examples on the main page of Vuetify, we come across the v-menu component showcased in detail. Check it out here: https://vuetifyjs.com/en/components/menus/#accessibility If you activate any of the buttons to open the v-menu and then scroll ...

Is there a way to update the input box value with a variable using jquery?

I am currently facing an issue with changing the value attribute of an input box in a form using jquery. Although I am able to change the value, it does not reflect in the outer html. Below is my current code snippet: $("a").click(function(event) { va ...

Trigger the onClick event when programmatically setting it as unchecked

My issue involves resetting a form when the user uses the browser's back-button. The form consists of multiple checkboxes, each with its own onClick event. Here is an example of one such checkbox: <input onclick="GetSelectedAmount();" class="Payme ...

Input field for postal code containing only numbers (maximum 5 digits) in Angular version 4/5

I am struggling with creating an input field that accepts numbers. If I use type="text", I can only type 5 characters of alphanumeric data, but if I use type="number", it allows any number input without limiting it to just 5 numbers. Thank you in advance f ...

Determine if a mobile application has been installed using Vue.js

I am currently developing a web application and have implemented a check to determine whether the user is accessing it from a mobile device or laptop. Let's consider the link as: my-site.com In addition to the web version, my site also offers a mobi ...