<@U04UQ68083H> How do I generate a JSON web token ...
# ory-copilot
b
@chilly-king-10285 How do I generate a JSON web token that is unique to a given Ory identity?
c
A message from kapa.ai
To generate a JSON Web Token (JWT) that is unique to a given Ory identity, you need to follow these steps: 1. Create a JSON Web Key Set: This can be done using the Ory CLI. The command to create a JSON Web Key set and store it locally is as follows:
Copy code
bash ory create jwk some-example-set \     --alg ES256 --project {project.id} --format json-pretty \     > es256.jwks.json
Replace
{project.id}
with your project's ID. 2. Create a JsonNet Template: This template will be used to modify the claims of the JWT. Here is an example of how to create a JsonNet template:
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 the Files: The easiest way to supply these files to Ory Network is to base64-encode them:
Copy code
bash JWKS_B64_ENCODED=$(cat es256.jwks.json | base64)   JSONNET_B64_ENCODED=$(cat claims.jsonnet | base64)
4. Configure the Tokenizer Templates: Next, configure your Ory Network project's tokenizer templates. The key chosen here is
jwt_example_template1
. Supply that template with the base64-encoded files from above:
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: Finally, you can convert an Ory Session to a JWT. Here is an example of how to do this using the Ory JS SDK:
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   }
Replace
{process.env.ORY_PROJECT_SLUG}
with your project's slug. For more details, refer to the [Ory documentation](https://www.ory.sh/docs/identities/session-to-jwt-cors#end-to-end-example).