<@U04UQ68083H> show me code example of how to use ...
# ory-copilot
m
@chilly-king-10285 show me code example of how to use oauth2TokenExchange
c
A message from kapa.ai
Sure, here is an example of how to exchange an authorization code for an access token using Ory. This code is written in JavaScript and uses the
fetch
function to make a POST request to the token URL.
Copy code
javascript const code = "authorization_code_received_from_auth_server"   const tokenUrl = "https://{project.slug}.<http://projects.oryapis.com/oauth2/token|projects.oryapis.com/oauth2/token>"   const requestBody = `grant_type=authorization_code&client_id=${clientId}&code_verifier=${codeVerifier}&code=${code}`      fetch(tokenUrl, {    method: "POST",    headers: { "Content-Type": "application/x-www-form-urlencoded" },    body: requestBody,   })    .then((response) => response.json())    .then((data) => console.log(data))    .catch((error) => console.error(error))
In this code, we exchange the authorization code received from the Authorization Server for an access token. We include the
code_verifier
parameter to validate the authorization code and prevent code injection attacks. You can find more details in the [Ory documentation](https://www.ory.sh/docs/oauth2-oidc/authorization-code-flow#exchange-code-for-token).