<@U04UQ68083H> is there a way to convert an opaque...
# ory-copilot
b
@chilly-king-10285 is there a way to convert an opaque access token (for example, one that you get from doing a login flow outside a browser) to a JWT?
c
A message from kapa.ai
No, there is no direct way to convert an opaque access token to a JWT. These are two different types of tokens that Ory can issue. An opaque token is a random string with a cryptographic signature that has no inherent meaning or structure. It is stored in a database, and its validity is checked by performing a database lookup. If you need to revoke an opaque token, you can simply delete it from the database. Once the token has been deleted, any subsequent attempts to use it will fail ([source](https://www.ory.sh/docs/oauth2-oidc/jwt-access-token#opaque-access-tokens-versus-jwt)). On the other hand, JWTs are self-contained and do not require a database lookup to validate. Instead, JWTs contain a signature that can be verified to ensure that the token has not been tampered with. Revoking a JWT requires a different approach, such as waiting for it to expire or using a blacklist or revocation list to mark the token as invalid ([source](https://www.ory.sh/docs/oauth2-oidc/jwt-access-token#opaque-access-tokens-versus-jwt)). If you want Ory to issue JWT access tokens instead of opaque tokens, you can configure this in the Ory settings. For all clients, you can update the configuration as follows:
Copy code
bash ory patch oauth2-config $PROJECT_ID \     --replace "/strategies/access_token=\"jwt\""
For a specific client, you can update the client configuration as follows:
Copy code
javascript import { Configuration, JsonPatch, 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 patchOAuth2Client(id: string, patches: JsonPatch[]) {     await ory.patchOAuth2Client({       id,       jsonPatch: [         ...patches,         {           op: "replace",           path: "access_token_strategy",           value: "jwt",         },       ],     })   }
These settings are also available through the Ory Console under the clients' settings ([source](https://www.ory.sh/docs/oauth2-oidc/jwt-access-token#per-client-configuration)).
b
@chilly-king-10285 is there a way to convert a session token (for example, one that you get from doing a login flow outside a browser) to a JWT?
c
A message from kapa.ai
Yes, Ory provides a way to convert a session token to a JSON Web Token (JWT). This can be useful in scenarios where you need to make a cross-origin request, need a JWT to represent a signed-in user, need to integrate with a third party, or want to reduce the number of calls to Ory's APIs. Here's a step-by-step guide on how to convert an Ory Session to a JWT: 1. First, create a JSON Web Key set and store it locally using the following command:
Copy code
bash ory create jwk some-example-set \     --alg ES256 --project $PROJECT_ID --format json-pretty \     > es256.jwks.json
2. Create a JsonNet template to modify the claims of the JWT:
Copy code
jsonnet local claims = std.extVar('claims');   local session = std.extVar('session');      {     claims: {       iss: claims.iss + "/additional-component",       schema_id: session.identity.schema_id,       session: session,     }   }
3. Base64-encode these files:
Copy code
bash JWKS_B64_ENCODED=$(cat es256.jwks.json | base64)   JSONNET_B64_ENCODED=$(cat claims.jsonnet | base64)
4. Configure your Ory Network project's tokenizer templates:
Copy code
bash ory patch identity-config $PROJECT_ID \     --add '/session/whoami/tokenizer/templates/jwt_example_template1={"jwks_url":"base64://'$JWKS_B64_ENCODED'","claims_mapper_url":"base64://'$JSONNET_B64_ENCODED'","ttl":"10m"}' \     --format yaml
5. Convert an Ory Session to a JWT:
Copy code
javascript import { Configuration, FrontendApi } from "@ory/client"      const frontend = new FrontendApi(     new Configuration({       basePath: `https://${process.env.ORY_PROJECT_SLUG}.<http://projects.oryapis.com|projects.oryapis.com>`,     }),   )      export async function toSessionWithJwt(sessionId: string) {     const session = await frontend.toSession({       tokenize_as: "jwt_example_template1",     })     const jwt = session.tokenized     return jwt   }
Please note that the session token can be obtained by calling the
toSession
endpoint from a non-browser application (e.g., a mobile app). The token is included in the
tokenized
field of the session ([source](https://www.ory.sh/docs/kratos/reference/api)). For more information, you can refer to the [Ory documentation on converting sessions to JWTs](https://www.ory.sh/docs/identities/session-to-jwt-cors).
b
@chilly-king-10285 is there a way to add custom fields to an OAuth Client, in the same way as adding public_metadata to an identity?
c
A message from kapa.ai
Yes, you can add custom fields to an OAuth client in Ory. However, these fields are not directly supported by the Ory API, so you will need to handle them in your own application logic. Here's an example of how you can add custom fields when creating an OAuth client:
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 createOAuth2Client() {   const { data } = await ory.createOAuth2Client({     client: {       client_id: "your-client-id",       client_secret: "your-client-secret",       // Add your custom fields here       custom_field_1: "custom value 1",       custom_field_2: "custom value 2",     },   })    return data }
Please note that these custom fields will not be recognized by Ory and will not be included in the client's metadata. You will need to handle these fields in your own application logic. For more information, you can refer to the [Ory documentation on managing OAuth clients](https://www.ory.sh/docs/hydra/sdk/go#createoauth2client-and-listoauth2clients).
b
@chilly-king-10285 is there a way to put the metadata for an Oauth client into the JWT when performing the client credential grant?
c
A message from kapa.ai
No, the Ory documentation does not provide a direct way to include the metadata of an OAuth client in the JWT when performing the client credential grant. The JWT claims are predefined and include the following fields:
iss
(issuer),
sub
(subject),
aud
(audience),
jti
(JWT ID),
exp
(expiration time), and
iat
(issued at time) ([source](https://www.ory.sh/docs/oauth2-oidc/client-credentials#jwt-bearer-profile-for-oauth2-client-authentication)). However, Ory does provide a way to customize the claims of a JWT by using a JsonNet template ([source](https://www.ory.sh/docs/identities/session-to-jwt-cors)). This could potentially be used to include additional information in the JWT, but it would require custom application logic to fetch the OAuth client's metadata and include it in the JWT. Please note that including sensitive information in a JWT is not recommended, as the contents of a JWT can be easily read by anyone who has access to the token. Always ensure that you are not including sensitive or confidential information in your JWTs.
b
@chilly-king-10285 is there a way to add custom fields to the JWT returned when performing the client credential grant with an OAuth client?
c
A message from kapa.ai
Yes, you can add custom fields to the JWT returned when performing the client credential grant with an OAuth client by using Ory's webhook feature. Here's how you can do it: 1. Register a webhook endpoint in your OAuth2 configuration. Before the token is issued to the client, Ory will call your HTTPS endpoint with information about the OAuth client requesting the token. 2. Your endpoint's response to the webhook will be used to customize the token that Ory issues to the OAuth client. You can add custom claims to the tokens issued by Ory OAuth2/Ory Hydra. Here's an example of how you can add custom claims to every access token during consent acceptance:
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)   }
This results in the following access token:
Copy code
json {     sub: "...",     // ...     ext: {       some_custom_claim: "some_custom_value",     },     // ...   }
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 ([source](https://www.ory.sh/docs/oauth2-oidc/jwt-access-token#custom-consent-ui-and-custom-claims-for-jwt-access-token)).