Should I use a custom JWT claim or query the db for authorization?

Solution for Should I use a custom JWT claim or query the db for authorization?
is Given Below:

Let’s say I have build a REST API for an application like WhatsApp and I got an endpoint like POST chats/groups/{group-id}/messages which adds a new chat message from my requestBody (This is just an example).

Before my API allow this request, it has to ensure that the request comes from a group member. So with that, I want to make sure that only group members are allowed to post new messages.

Since I didn’t want to query the database for group membership, everytime I post a message to the group, I thought about adding custom claims to the JWT.
Could look like this

 "groupMemberships": ["Some fancy UUID", "This one is a fancy UUID as well"], 

With that I always could compare if the requester contains the target group in it’s groupMembership array via the UUID. Sounds fine until now…

But what happens when the user is kicked out from the group ? Since the JWT is valid for e.g. 2 weeks, the requester could still send messages to the group, which is creepy and weird at the same time. A possible solution could be to blacklist the JWT but that’s not really what I want, since that steals the stateless characteristic and lets me hit the DB anyway.

How could someone solve this problem ? Is it maybe okay to query the db for membership checks ?

One risk with your approach is that for some users the token might be quite big (what if you are part of many groups?). In general you want to keep your tokens small.

Another option is o let the API that receives the access token, do a lookup against your database as this is part of the authorization phase. By doing this, you can have long lived access tokens and the user can change groups as you like.

Alternatively, if you do add the claim to the token, you can then make the access token short lived, like 5 minutes, and have a long lived refresh token to renew and update the claims in the access token.