Adding custom claims in JWT using golang

Please include the following information in your post:

  • Which SDK this is regarding: e.g. golang
  • Platform Version: e.g Golang 1.15.6

I am trying to implement auth using golang. I am able to get the JWT code as mentioned in this article (Auth0 Go API SDK Quickstarts: Authorization). After getting the JWT code, I want to add some custom claims (say items_list) to it. I am unable to understand how to do that. Can anyone please help me understand how to do it?

(PS: I just came to know there is something like rules, but for that my users will have to do it by themselves which I am not sure is good. Still, any help related to that in addition would be appreciated)

Thank you very much in advance.

The JWT once it is issued by Auth0, it is digitally signed so it can not be changed. The only way to add custom data on it is by using rules, which runs right before the token is issued and return to the client application. If you want to add custom data after it is issued, you will have to issue a new token with the aggregated data and signed by a key on your end, which is not a good idea at all (this is usually called self-signed tokens).

2 Likes

Thank you for replying. I am having a shortage of time to go through entire docs for rules.

Can you please tell me the rule for adding a custom claim, say items_list such that the JWT then generated will have that custom claim in it?
(Will make my life a lot easier)

Thank you very much in advance.

Certainly.

function (user, context, callback) {
const namespace = โ€˜http://demozero.netโ€™;
const items = [โ€˜1โ€™,โ€˜2โ€™,โ€˜3โ€™]

let idTokenClaims = context.idToken || {};
let accessTokenClaims = context.accessToken || {};

idTokenClaims[${namespace}/items] = items;
accessTokenClaims[${namespace}/items] = items;

context.idToken = idTokenClaims;
context.accessToken = accessTokenClaims;

callback(null, user, context);
}

2 Likes

Thanks for sharing that with the rest of community @cibrax!

Thank you for your reply. I am still stuck on how do I create the token that contains those items claims.

I tried using the above example of what @cibrax said and created a rule. Now when I am trying to print the custom claims using Auth0 Go API SDK Quickstarts: Authorization example and do the print via token.Claims and it does not show me the items list.

Thank you!

Update: I still do not notice the items array after printing the profiles map from this tutorial. Auth0 Go SDK Quickstarts: Login

Can anyone please tell me where am I wrong?

I am now abe to get the items list when printing the profile here Auth0 Go SDK Quickstarts: Login, but the doubt remains how to create a JWT token that has those items and then I can decode using a public key as described here Auth0 Go API SDK Quickstarts: Authorization.

Thank you very much