Search code examples
oauth-2.0authorizationkeycloakopenid

Keycloak OpenID Connect redirect_uri behaves inconsistently


I have Keycloak 22.0.5 deployed via docker on my local machine. I have a custom OpenID client configured with its access as follows: Keycloak Access Settings page configured with: Root URL - empty, Home URL - http://localhost:8000, Valid redirect URIs - http://localhost:8000/*, Valid post logout redirect Uris - +, Web Origins - empty, Admin URL - empty I don't want to use a password grant, I'm using pkce (authorization_code variation) grant instead (same way as account-console does it).

That's the request I'm sending to the server for authentication:

GET localhost:2137/realms/SpringKeycloak/protocol/openid-connect/auth?
    client_id=login-user
    &redirect_uri=http%3A%2F%2Flocalhost%3A8000
    &state=af08ea5a-9d4d-4850-9491-483809f2c991
    &response_type=code
    &scope=openid
    &code_challenge=Jqd4T8zNX438YOgW-99eFp_7fbMkDb1Tyu0TtU41x3A
    &code_challenge_method=S256
    &grant_type=pkce

Now, the thing is this works perfectly fine, but when I try to get the token, using same redirect_uri:

POST localhost:2137/realms/SpringKeycloak/protocol/openid-connect/token

code=ed24eb7c-ef7e-4c51-b545-c59e0717f6a1.54c25efe-7721-4d81-9f64-99493ee365b9.a2b82e1f-84c7-464f-a555-dcea26162e5a
&grant_type=authorization_code
&client_id=login-user
&redirect_uri=http%3A%2F%2Flocalhost%3A8000
&code_verifier=0a844a24ec41aeb96bc016d8d488794802a066378bbfd35bb8adcf55

However it claims, that the url now is invalid:

{
    "error": "invalid_grant",
    "error_description": "invalid parameter: redirect_uri"
}

And I don't know what could be causing this behavior. I've looked both through config and through the internet, but I can't find any additional setting that could be causing it.

I've also tried changing the grant type in the second request to pkce same way as the first one, but it just raises unsupported_grant_type


Solution

  • When exchanging the code for tokens, you have to submit all parameters via HTTP POST (x-www-form-urlencoded). In that case, the redirect_uri must NOT be urlencoded, as most likely your tool performing the HTTP POST does the URL encoding for you.

    Also, if you use e.g. Postman, it seems that you send the parameters in HTTP POST via "Params" and not via "Body -> x-www-form-urlencoded".