<@U04UQ68083H> how can i perform token exchange af...
# ory-copilot
r
@chilly-king-10285 how can i perform token exchange after the ory kratos session has been set in user browser
b
A message from kapa.ai
To perform a token exchange after the Ory Kratos session has been set in the user's browser, you typically use the session token exchange flow. This is especially relevant for native or mobile applications that need to convert a browser-based session into a session token for API use. ### Steps for Token Exchange 1. Initialize the Login/Registration Flow with Token Exchange Enabled - When starting the login or registration flow, set the
return_session_token_exchange_code=true
parameter. This instructs Ory to provide a code that can later be exchanged for a session token. - Example (TypeScript/React Native):
Copy code
typescript      const flow = await frontend.createNativeLoginFlow({        return_session_token_exchange_code: true,        // other params...      })
- The response will include an
init_code
as part of the flow data. 2. User Authenticates in the Browser - The user completes authentication (including social sign-in if applicable) in the browser. After successful authentication, Ory will redirect the browser to your specified
return_to
URL, including a
code
parameter (
return_to_code
) in the query string. 3. Exchange the Codes for a Session Token - Your native/mobile app should now have both: - The
init_code
from the flow initialization. - The
return_to_code
from the redirect URL after authentication. - Call the
/sessions/token-exchange
endpoint with both codes:
Copy code
http      GET /sessions/token-exchange?init_code=<init_code>&return_to_code=<return_to_code>
- This will return a session token that you can use for authenticated API requests. #### Example API Call
Copy code
bash curl "https://<your-ory-project>.<http://projects.oryapis.com/sessions/token-exchange?init_code=<init_code>&return_to_code=<return_to_code|projects.oryapis.com/sessions/token-exchange?init_code=<init_code>&return_to_code=<return_to_code>>"
#### Notes - This flow is designed for native/mobile apps, not for browser-based SPAs or server-side web apps. - If you already have a session in the browser, you should only use this flow if you need to obtain a session token for use outside the browser context (e.g., in a mobile app or API client). For more details, see the [Ory Kratos API reference for token exchange](https://raw.githubusercontent.com/ory/kratos/master/spec/api.json) and the [Ory documentation on social sign-in for native apps](https://www.ory.sh/docs/kratos/social-signin/native-apps#implementation) and [token exchange endpoint](https://raw.githubusercontent.com/ory/docs/master/docs/reference/api.json).
r
@chilly-king-10285 I’m using browser based, but I would still like to have JWT in browser flow
b
A message from kapa.ai
Yes, you can obtain a JWT in a browser-based flow with Ory Kratos by converting the session to a JWT after the user is authenticated. By default, Ory Kratos issues a session cookie for browser flows, not a JWT. However, Ory provides a mechanism to convert the session into a JWT using the Session to JWT feature. ### How to Get a JWT in a Browser Flow 1. Authenticate the User via the Standard Browser Flow The user logs in as usual, and Ory sets the session cookie in the browser. 2. Call the
/sessions/whoami
Endpoint with Tokenization
To obtain a JWT, call the
/sessions/whoami
endpoint and use the
tokenize_as
query parameter with your configured JWT template. Example using the Ory JS SDK:
Copy code
typescript    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() {      const session = await frontend.toSession({        tokenize_as: "jwt_example_template1", // Use your configured template name      })      const jwt = session.tokenized      return jwt    }
Or with cURL:
Copy code
bash    curl -X GET \      -H "Cookie: ory_session...=..." \      "https://$<http://PROJECT_SLUG.projects.oryapis.com/sessions/whoami?tokenize_as=jwt_example_template1|PROJECT_SLUG.projects.oryapis.com/sessions/whoami?tokenize_as=jwt_example_template1>"
The response will include a
tokenized
field containing the JWT. 3. Configure JWT Templates You must configure a JWT template in your Ory project before using this feature. This involves creating a JWK set and a claims mapping template, then patching your project configuration to add the template. [See the full setup guide here.](https://www.ory.sh/docs/identities/session-to-jwt-cors) ### Important Notes - This approach is recommended for scenarios where you need a JWT in the browser, such as for CORS requests or integrating with third-party services. - The session cookie remains the default and most secure way to manage sessions in browser-based applications. JWTs are best used when you have a specific need for them. For more details and a step-by-step example, refer to the official documentation: [Convert Ory Sessions to JSON Web Tokens](https://www.ory.sh/docs/identities/session-to-jwt-cors) and [Session-management overview](https://www.ory.sh/docs/kratos/session-management/overview#json-web-token-jwt-support).