ERRATA - Keycloak and NextJS demo

I published these videos about integrating a simple NextJS app with Keycloak a few months ago.

Since then, I've learned a bit more. There are two things I wouldn't recommend doing, if I were to make that integration again today.

First, regarding the access token. In the demo, I look inside the access token to see if the user has a certain claim. In OAuth2, you're not supposed to do that. Access tokens can be opaque, meaning their JSON encoding is not guaranteed. An access token might be a simple Guid or magic string that you send forward when accessing resources. It's the job of the resource server to verify if that token is valid.

My recommendation: do not look inside the Access token in your client app. If you need to know some information about the user, you have two options: you can either query a service (like the /userinfo endpoint or the introspection endpoint if available) using your access token, or you can configure the auth server to include the claim that you need in the ID Token (this one is guaranteed to be encoded as JWT).

The second point is about token introspection. In the demo, I implemented it in such a way that every time it received the token, it would call the introspection endpoint to check the validity of the token. I wouldn't say this is approach is wrong, but it's probably inefficient, due to the constant network calls. If you have a lot of concurrent users, you may have a problem.

An alternative is to not use introspection at all upon receiving an access token. Instead, you should opt for short lived access tokens. Let's say, with a 5 minutes lifespan. If access is somehow revoked (e.g. the user is disabled, the consent is withdrawn, the permission is removed, etc.), the maximum duration the user will be able to stay with the old access is 5 minutes, which is likely acceptable. The next time they try to renew the access token using a refresh token, if the user is no longer authorized, the refresh process will fail. This approach is stateless and, in general, more efficient.