billions-minister-2901
06/24/2025, 8:35 PMbrief-egg-61061
06/24/2025, 8:35 PMbrief-egg-61061
06/24/2025, 8:36 PMory perform client-credentials \ --client-id="your_client_id" \ --client-secret="your_client_secret" \ --project "your_project_id"
Or programmatically: javascript const fetch = require("node-fetch") const accessToken = "your_access_token_here" fetch("<https://api.example.com/resource>", { headers: { Authorization: "Bearer " + accessToken, }, }) .then((response) => response.json()) .then((data) => console.log(data)) .catch((error) => console.error(error))
## Authorization Code Grant For applications that need to act on behalf of users, you can use the Authorization Code Grant. After obtaining an authorization code, you exchange it for an access token: ory perform authorization-code \ --project "your_project_id" \ --client-id "your_client_id" \ --client-secret "your_client_secret"
[OAuth2 Authorization Code Flow](https://www.ory.sh/docs/oauth2-oidc/authorization-code-flow#step-4-exchange-code-for-token) requires sending a POST request to the Authorization Server with: - `grant_type`: Set to authorization_code
- `client_id`: Your client ID - `client_secret`: Your client secret - `code`: The authorization code received - `redirect_uri`: The same redirect URI used in the original request ## Framework-Specific Examples For Next.js: javascript // pages/api/oauth/token.ts import type { NextApiRequest, NextApiResponse } from 'next'; import jackson from '../../../../lib/jackson'; export default async function handler( req: NextApiRequest, res: NextApiResponse ) { const { oauthController } = await jackson(); const response = await oauthController.token(req.body); return res.json(response); }
[Next.js Implementation](https://www.ory.sh/docs/polis/guides/frameworks/nextjs#request-access-token) For Express.js: javascript router.get("/sso/callback", async (req, res, next) => { const { code, state } = req.query const tenant = "<http://boxyhq.com|boxyhq.com>" // The user's tenant const product = "<http://saml-demo.boxyhq.com|saml-demo.boxyhq.com>" // Your app or product name const clientId = `tenant=${tenant}&product=${product}` const clientSecret = "dummy" // Exchange the `code` for `access_token` const { access_token } = await oauthController.token({ code, client_id: clientId, client_secret: clientSecret, redirect_uri: redirectUrl, }) })
[Express.js Implementation](https://www.ory.sh/docs/polis/guides/frameworks/express#request-access-token) Remember that access tokens are meant for API access, while ID tokens (in OpenID Connect) are for authentication purposes.billions-minister-2901
06/24/2025, 8:37 PMbrief-egg-61061
06/24/2025, 8:37 PMbrief-egg-61061
06/24/2025, 8:37 PMjavascript const clientId = "your_client_id" const redirectUri = "<https://myapp.com/callback>" const state = generateRandomString() // For CSRF protection const authorizationUrl = `https://$<http://PROJECT_SLUG.projects.oryapis.com/oauth2/auth?response_type=code&client_id=${clientId}&redirect_uri=${redirectUri}&scope=openid%20offline_access&state=${state}|PROJECT_SLUG.projects.oryapis.com/oauth2/auth?response_type=code&client_id=${clientId}&redirect_uri=${redirectUri}&scope=openid%20offline_access&state=${state}>` // Redirect the user to the Authorization Server window.location = authorizationUrl
For better security, especially with public clients, you should use PKCE (Proof Key for Code Exchange): javascript // Generate PKCE code challenge and verifier async function generatePKCES256() { const array = new Uint8Array(64) crypto.getRandomValues(array) const codeVerifier = Buffer.from(array).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_") const codeChallenge = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(codeVerifier)).then((buffer) => { return Buffer.from(buffer).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_") }) return { codeChallenge, codeVerifier } } const { codeChallenge, codeVerifier } = await generatePKCES256() const authorizationUrl = `https://$<http://PROJECT_SLUG.projects.oryapis.com/oauth2/auth?response_type=code&client_id=${clientId}&redirect_uri=${redirectUri}&code_challenge=${codeChallenge}&code_challenge_method=S256&scope=openid,offline|PROJECT_SLUG.projects.oryapis.com/oauth2/auth?response_type=code&client_id=${clientId}&redirect_uri=${redirectUri}&code_challenge=${codeChallenge}&code_challenge_method=S256&scope=openid,offline>`
[OAuth2 Authorization Code Flow with PKCE](https://www.ory.sh/docs/oauth2-oidc/authorization-code-flow#perform-pkce) ## 2. Handle the Redirect and Extract the Code After the user authenticates and consents, they will be redirected to your redirect_uri
with the authorization code as a query parameter: javascript // For browser applications const urlParams = new URLSearchParams(window.location.search); const code = urlParams.get('code'); const state = urlParams.get('state'); // Verify that the state matches what you sent if (state !== originalState) { // Potential CSRF attack throw new Error('State validation failed'); } // Now you have the authorization code console.log('Authorization Code:', code);
For server-side applications, you would extract the code from the request query parameters. ## 3. Exchange the Code for Tokens Once you have the authorization code, you can exchange it for tokens: javascript const tokenUrl = "https://$<http://PROJECT_SLUG.projects.oryapis.com/oauth2/token|PROJECT_SLUG.projects.oryapis.com/oauth2/token>" const requestBody = new URLSearchParams({ grant_type: "authorization_code", client_id: clientId, client_secret: clientSecret, // For confidential clients code: code, redirect_uri: redirectUri, code_verifier: codeVerifier // If using PKCE }) fetch(tokenUrl, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: requestBody.toString() }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error))
[SPA and Public Client with PKCE](https://www.ory.sh/docs/oauth2-oidc/authorization-code-flow#spa-and-public-client-with-pkce) For testing purposes, you can also use the Ory CLI: bash ory perform authorization-code \ --client-id "your_client_id" \ --client-secret "your_client_secret" \ --project "your_project_id"
[Try Common OAuth2 Grants](https://www.ory.sh/docs/getting-started/ory-network-oauth2#authorization-code-grant) Remember that the authorization code is short-lived and can only be used once to exchange for tokens.