Grafana gets 401 when getting userinfo from Keycloak

  • What Grafana version and what operating system are you using?
    I am running the grafana/grafana:10.3.3 docker container on Ubuntu

  • What are you trying to achieve?
    I want to set Keycloak as the authentication method for Grafana

  • How are you trying to achieve it?
    I have a single server where I am hosting both Grafana and Keycloak. I did everything as stated in Configure Keycloak OAuth2 authentication | Grafana documentation except I am using environment variables in the container instead of the .ini file. I’m not sure why, but I had to use the container name instead of the endpoint that I use for Grafana webapp for both token url and API URL, otherwise I had a timeout.

  • What happened?
    Now I can login, but I cannot get the userinfo nor the roles that I set on Keycloak. The logs say that I am getting the information about the user only from the id token. The /userinfo endpoint actually responds with a 401 Unathorized error code.

  • What did you expect to happen?
    I expected to be able to get the user info and mainly the roles from Keycloak into Grafana.

  • Can you copy/paste the configuration(s) that you are having problems with?
    auth-keycloak-1 is the name of the keycloak container
    The following are my env variables:

  - GF_AUTH_GENERIC_OAUTH_SCOPES=openid email profile offline_access roles
  - GF_AUTH_GENERIC_OAUTH_TOKEN_URL=http://auth-keycloak-1:8080/realms/myrealm/protocol/openid-connect/token
  - GF_AUTH_GENERIC_OAUTH_API_URL=http://auth-keycloak-1:8080/realms/myrealm/protocol/openid-connect/userinfo
  - GF_AUTH_GENERIC_OAUTH_ROLE_ATTRIBUTE_PATH=contains(resource_access.grafana.roles[\*], 'admin') && 'Admin' || contains(resource_access.grafana.roles[\*], 'editor') && 'Editor' || 'Viewer'
  - GF_LOG_LEVEL=debug
  • Did you receive any errors in the Grafana UI or in related logs? If so, please tell us exactly what they were.
    I saw logs like this:

logger=oauthtoken t=2024-03-19T23:03:39.612815605Z level=error msg=“Failed to retrieve oauth access token” provider=oauth_generic_oauth userId=2 error=“oauth2: "invalid_grant" "Invalid token issuer. Expected ‘http://auth-keycloak-1:8080/realms/myrealm’"”

, but if I substitute the container name with the “external” address I get an i/o timeout. Definitely not a network issue though, because I can reach Keycloak console that is exposed over the same IP and port of the server.

That indicates networking issue, so fix that
configure Keycloak to return issuer, which doesn’t depend on used hostname (how to do that is out of scope for Grafana forum)