Golang get openid-connect userinfo

It might not be news to you, but this will explain a little bit about Go, making http requests and parsing the result.

OpenID-Connect (oidc) is an identity protocol, you could call it an Oauth2 dialect. It manages your users per realm, well not the protocol but the server does.
Every oidc idp (identity provider aka server) should support the oidc discovery feature.
What is a good OIDC IDP? Keycloak for instance, because it’s free.
Essentially it’s a well known URI that provides information about this IDP or this IDP’s realm in JSON.
The “.well-known/openid-configuration” is appended to the IDP.
To see a live one you could navigate to https://connect.icod.de/auth/realms/testrealm/.well-known/openid-configuration

It lists all the endpoints this server handles and supported grant types and much much more.

I’ve been working with websockets lately and faced the challenge that websockets don’t support passing HTTP headers,
so I had to log in with the token my frontend received by the IDP. And for security reasons this had to be the raw token, not the parsed subject field, because it’s not cryptographically protected.
This means I had to ask the IDP if the token I had received was valid and extract the subject from it.

The below code is the 1st version of how I did it.
It queries the openid-connect discovery document, since the structure was unknown to me, I decoded the response body from the request into a map[string]interface{}.
However in retrospect, I could’ve defined a struct with only the single requested variable in it:

Then this userinfo endpoint is queried with the Accesstoken passed as a Bearer token in the Authorization header.
The result is decoded into the UserInfo struct instance and returned by the function.

I use spew, which is a very helpful tool to display the content of the returned variable.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.