Getting "invalid_grant" during client token request using authorization code

I’m following the implementer’s guide from https://openid.net/specs/openid-connect-basic-1_0.html. I’m trying to use the authorization code that is presented to the end-user after login. According to 2.1.6.1. Client Sends Code I should be able to POST to “/auth/realms/{realm}/protocol/openid-connect/token” with the following parameters grant_type and code. I’m getting the error invalid_grant with the description of “Code not valid”. It seems like an easy fix except that I’m using the code from the authentication response.

Authentication 302 response:
Location: http://IPADDR:PORT/?session_state=a73add8c-2404-4d25-8d58-f7a9bd81b041&code=0668a692-e80e-4835-8244-ea6d76e17307.a73add8c-2404-4d25-8d58-f7a9bd81b041.6c9bd3fc-908a-40fe-b581-18b2c1316594

POST to validate:
POST /auth/realms/{realm}/protocol/openid-connect/token HTTP/1.1
Host: IPADDR:8443
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 240
Origin: https://IPADDR:8443
Authorization: Basic BASE64ENCODED(CLIENT_ID:SECRET)

grant_type=authorization_code&code=0668a692-e80e-4835-8244-ea6d76e17307.a73add8c-2404-4d25-8d58-f7a9bd81b041.6c9bd3fc-908a-40fe-b581-18b2c1316594

See: Getting started with Keycloak

1 Like

Thanks I’ll check it out!

Dear @arozar I’m getting the same error when using authorization_code as the grant_type. Did you solve your problem?
Thanks in advance

I’ve seen this too.

/app/oauth2/loginCallback?session_state=yadayada&code=yadayada

When we then try to use that code to get tokens from keycloak we have seen - one single time only - :

{"error":"invalid_grant","error_description":"Code not valid"}

We didn’t see it in test, and now in prod we’ve seen thousands of successful logins, but this error once.

It sounds like perhaps @arozar has a different issue if he is seeing this consistently…

If anybody has ideas…