<@U04UQ68083H> how to add custom fields to JWT, bo...
# ory-copilot
b
@chilly-king-10285 how to add custom fields to JWT, both for client credentials grant for machine to machine auth and when calling toSession to convert a session token to a JWT
c
A message from kapa.ai
To add custom fields to JWT, you can follow these steps: 1. For client credentials grant for machine-to-machine authentication: Unfortunately, the provided knowledge sources do not contain specific information on how to add custom fields to JWT for client credentials grant for machine-to-machine authentication. 2. When calling toSession to convert a session token to a JWT: You can add custom claims to every access token during consent acceptance. Here is an example code snippet:
Copy code
javascript    import { Configuration, OAuth2Api } from "@ory/client"         const ory = new OAuth2Api(        new Configuration({          basePath: `https://${process.env.ORY_PROJECT_SLUG}.<http://projects.oryapis.com|projects.oryapis.com>`,          accessToken: process.env.ORY_API_KEY,        }),      )         export async function acceptConsent(consentChallenge: string) {        const { data } = await ory.getOAuth2ConsentRequest({ consentChallenge })           return await ory          .acceptOAuth2ConsentRequest({            consentChallenge: consentChallenge,            acceptOAuth2ConsentRequest: {              session: {                access_token: {                  some_custom_claim: "some_custom_value",                },                id_token: {                  id_custom_claim: "some_value",                },              },            },          })          .then(({ data }) => data)      }
If you want
some_custom_claim
to be added to the top level (instead of a nested level) in the access token, you need to modify the
/oauth2/allowed_top_level_claims
configuration:
Copy code
bash    ory patch oauth2-config {project.id} \        --replace "/oauth2/allowed_top_level_claims=[\"some_custom_claim\"]"
This results in an access token with the following structure:
Copy code
json    {        "sub": "...",        // ...        "some_custom_claim": "some_custom_value",        "ext": {          "some_custom_claim": "some_custom_value"        }        // ...      }
Please note that required JWT claims can't be overwritten by custom claims. For more detailed information, please refer to the [Ory documentation](https://www.ory.sh/docs/oauth2-oidc/jwt-access-token#custom-consent-ui-and-custom-claims-for-jwt-access-token).
b
@chilly-king-10285 when using a JWT tokenizer template, how would you map the user's permissions into a claim?
c
A message from kapa.ai
To map the user's permissions into a claim when using a JWT tokenizer template, you would need to use a JsonNet template provided to
claims_mapper_url
. This template has access to the
claims
and
session
variables, which contain the default claims and the Ory Session's data respectively. Here's an example of how you might do this:
Copy code
jsonnet local claims = std.extVar('claims');   local session = std.extVar('session');      {     claims: {       permissions: session.permissions, // assuming the permissions are stored in the session data     // other claims...   }   }
In this example,
session.permissions
is used to set the
permissions
claim. This assumes that the user's permissions are stored in the session data. If they are stored elsewhere, you would need to adjust this accordingly. Please note that the
sub
claim cannot be customized and is always set to the Ory Session's
IdentityID
. For more information, refer to the [Ory documentation](https://www.ory.sh/docs/identities/session-to-jwt-cors#json-web-token-claim-mapper).
b
@chilly-king-10285 how to call the api or sdk to get all permissions for a given user?
c
A message from kapa.ai
To get all permissions for a given user, you can use the Ory Keto API. Here's an example of how you might do this: First, you need to get all groups for the user. In this example, we're getting all groups for a user named Dilan:
Copy code
bash keto relation-tuple get --subject-id=Dilan --relation=member --format json --read-remote localhost:4466 | jq
This will return a list of groups that Dilan is a member of. For each group, you can then get the permissions for objects related to that group. Here's an example of how you might do this for a group named "marketing":
Copy code
bash keto relation-tuple get --subject-set="groups:marketing#member" --format json --read-remote localhost:4466 | jq
This will return a list of permissions for objects related to the "marketing" group. Please note that these examples use the command line interface for Ory Keto. If you're using a programming language, you would use the corresponding SDK instead. For example, in Python, you would use the
check_permission
method of the
PermissionApi
class to check permissions. For more information, refer to the [Ory Keto documentation](https://www.ory.sh/docs/keto/guides/rbac#display-all-objects-a-user-has-access-to).
b
@chilly-king-10285 does this add a webhook for all oauth clients, and if so how do I add it for only one client?
Copy code
ory patch oauth2-config $project_id \
--add '/oauth2/token_hook="<https://my-example.app/token-hook>"' \
--format yaml
c
A message from kapa.ai
The command you provided:
Copy code
bash ory patch oauth2-config $project_id \ --add '/oauth2/token_hook="<https://my-example.app/token-hook>"' \ --format yaml
This command is used to register a webhook endpoint for the OAuth2 configuration. This webhook will be called before a token is issued to any client. Therefore, it applies to all OAuth clients, not just one. The webhook is called with information about the OAuth client requesting the token. If you want to customize the response for a specific client, you could do so within the webhook itself by checking the client information in the webhook payload. Unfortunately, the provided knowledge sources do not contain specific information on how to add a webhook for only one client. For more detailed information, please refer to the [Ory documentation](https://www.ory.sh/docs/hydra/guides/claims-at-refresh).
b
@chilly-king-10285 add custom claims when calling toSession to get JWT. Can we query for the user's permissions and add those into the JWT?
c
A message from kapa.ai
Yes, you can add custom claims when calling
toSession
to get a JWT. However, the process of querying for the user's permissions and adding those into the JWT would depend on how you have structured your application and where the permissions are stored. Here's a general approach: 1. Query for the user's permissions from your database or wherever they are stored. 2. Add the permissions to the session data. 3. Use a JsonNet template to map the permissions from the session data to a claim in the JWT. Here's an example of how you might do this in the JsonNet template:
Copy code
jsonnet local claims = std.extVar('claims');   local session = std.extVar('session');      {     claims: {       permissions: session.permissions, // assuming the permissions are stored in the session data     // other claims...   }   }
In this example,
session.permissions
is used to set the
permissions
claim. This assumes that the user's permissions are stored in the session data. If they are stored elsewhere, you would need to adjust this accordingly. Please note that the
sub
claim cannot be customized and is always set to the Ory Session's
IdentityID
. For more information, refer to the [Ory documentation](https://www.ory.sh/docs/identities/session-to-jwt-cors#json-web-token-claim-mapper).
b
@chilly-king-10285 how would you add something to the session data?
c
A message from kapa.ai
Adding data to the session can be done during the consent flow. When a user logs in, a consent request is created. You can fetch this consent request, add data to the session, and then accept the consent request with the updated session data. Here's an example of how you might do this:
Copy code
javascript oauth2   .getOAuth2ConsentRequest({ consentChallenge: challenge })   .then(async ({ data: body }) => {     const session = await createOAuth2ConsentRequestSession(       grantScope,       body,       identity,     )     // Add data to the session here   session.some_custom_data = "some_value";   return oauth2     .acceptOAuth2ConsentRequest({       consentChallenge: challenge,       acceptOAuth2ConsentRequest: {         grant_scope: grantScope,         session: session,         grant_access_token_audience: body.requested_access_token_audience,         remember: Boolean(req.body.remember),       },     })   })
In this example,
some_custom_data
is added to the session. This data will then be included in the ID token and access token when they are issued. For more information, refer to the [Ory documentation](https://www.ory.sh/docs/oauth2-oidc/custom-login-consent/flow#consent-endpoint-code-example).