polite-finland-81696
06/12/2024, 1:19 PMchilly-king-10285
06/12/2024, 1:19 PMchilly-king-10285
06/12/2024, 1:20 PMoffline_access
scope in the access request. The client needs to be allowed to request the offline_access
scope and the user has to accept that the client may use the offline_access
scope on the consent screen. The offline_access
scope allows the requesting application to obtain a refresh token that can be used to obtain a new access token without requiring the user to re-authenticate. Here is an example of how you can exchange the authorization code received from the Authorization Server for an access token: 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, the code_verifier
parameter is included to validate the authorization code and prevent code injection attacks. For more details, you can refer to the following sources: - [Get a refresh token](https://www.ory.sh/docs/oauth2-oidc/authorization-code-flow#get-a-refresh-token) - [Exchange code for token](https://www.ory.sh/docs/oauth2-oidc/authorization-code-flow#exchange-code-for-token)polite-finland-81696
06/12/2024, 1:20 PMchilly-king-10285
06/12/2024, 1:20 PMchilly-king-10285
06/12/2024, 1:21 PMjavascript // Set up the endpoint and refresh token const endpoint = "<https://oauth2.example.com/token>" const refreshToken = "<refresh token>" const clientId = "<client id>" const clientSecret = "<client secret>" const params = new URLSearchParams({ grant_type: "refresh_token", refresh_token: refreshToken, scope: "scope1 scope2", client_id: clientId, client_secret: clientSecret, }) // Send a POST request to refresh the access token fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", }, body: params.toString(), }) .then((response) => { if (!response.ok) { throw new Error("Failed to refresh access token") } return response.json() }) .then((data) => { console.log("New access token:", data.access_token) console.log("New ID token:", data.id_token) console.log("New refresh token:", data.refresh_token) }) .catch((error) => { console.error(error) })
In this example, a POST request is made to the token endpoint of the Ory server. The request body includes the refresh token, client ID, and client secret. The server responds with a new access token, ID token, and refresh token. For more details, you can refer to the following source: - [Refreshing an access token](https://www.ory.sh/docs/oauth2-oidc/refresh-token-grant#refreshing-an-access-token)