<@U04UQ68083H> how do i exchange ory session to jw...
# ory-copilot
m
@chilly-king-10285 how do i exchange ory session to jwt?
c
A message from kapa.ai
To convert an Ory Session to a JSON Web Token (JWT), you need to follow these steps: 1. 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 that will be used to modify the claims of the JWT. The template should look like this:
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 to supply them to Ory Network:
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. The key we choose here is
jwt_example_template1
. We 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 using the Ory JS SDK or REST API:
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   }
6. Verify the resulting JSON Web Token by exporting the public key from the JSON Web Key Set and using it to verify the token:
Copy code
bash ory get jwk some-example-set \    --public \    --project {project.id} --format json-pretty \    > es256-public.jwks.json
For more details, you can refer to the [Ory documentation](https://www.ory.sh/docs/identities/session-to-jwt-cors#end-to-end-example).