Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keycloak Missing form parameter: grant_type

I have keycloak standalone running on my local machine.

I created new realm called 'spring-test', then new client called 'login-app'

According to the rest documentation:

POST: http://localhost:8080/auth/realms/spring-test/protocol/openid-connect/token

{
    "client_id": "login-app",
    "username": "user123",
    "password": "pass123",
    "grant_type": "password"
}

should give me the jwt token but I get bad request with response

{
    "error": "invalid_request",
    "error_description": "Missing form parameter: grant_type"
}

I am assuming that something is missing in my configuration.

EDIT: I was using json body but it should be application/x-www-form-urlencoded: the following body works:

token_type_hint:access_token&token:{token}&client_id:{client_id}&client_secret:{client_secret}
like image 648
Borislav Stoilov Avatar asked Dec 15 '18 16:12

Borislav Stoilov


3 Answers

You should send your data in a POST request with Content-Type header value set to application/x-www-form-urlencoded, not json.

like image 175
ipave Avatar answered Oct 20 '22 10:10

ipave


With Curl

curl -X POST \
http://localhost:8080/auth/realms/api-gateway/protocol/openid-connect/token \
-H 'Accept: */*' \
-H 'Accept-Encoding: gzip, deflate' \
-H 'Cache-Control: no-cache' \
-H 'Connection: keep-alive' \
-H 'Content-Length: 73' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-H 'Cookie: JSESSIONID=F8CD240FF046572F864DC37148E51128.a139df207ece;   JSESSIONID=65D31B82F8C5FCAA5B1577DA03B4647C' \
-H 'Host: localhost:8080' \
-H 'Postman-Token: debc4f90-f555-4769-b392-c1130726a027,d5087d9f-9253-48bd-bb71-fda1d4558e4d' \
-H 'User-Agent: PostmanRuntime/7.15.2' \
-H 'cache-control: no-cache' \
-d 'grant_type=password&client_id=api-gateway&username=admin&password=temp123'

By Postman (Select x-www-form-urlencoded option for parameters)

enter image description here

like image 20
Robin Mathur Avatar answered Oct 20 '22 10:10

Robin Mathur


For those who landed here from a search looking for JavaScript solution.

Here is an example when exchanging code for access_token with keycloak authority using axios.

Sending the request:


const params = new URLSearchParams({

    grant_type: 'authorization_code',
    client_id: 'client-id-here',
    code: 'code-from-previous-redirect',
    redirect_uri: location.protocol + '//' + location.host

});

axios({

    method: 'post',
    url: 'https://my-keycloak.authority/token',
    data: params.toString(),
    config: {
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }

}).then(response => {

    console.log(response.data);

}).catch(error => {

    console.error(error);

});

You are required to send a POST request with the parameters as a URL encoded string in the request body.

FormData object does not work.

like image 18
Marc Avatar answered Oct 20 '22 12:10

Marc