<@U04UQ68083H> Can I get an access token via the A...
# ory-copilot
b
@chilly-king-10285 Can I get an access token via the API?
b
A message from kapa.ai
Yes, you can get an access token via the API in Ory using different OAuth2 grant types depending on your use case. ## Client Credentials Grant For machine-to-machine communications without user interaction, you can use the Client Credentials Grant:
Copy code
ory perform client-credentials \   --client-id="your_client_id" \   --client-secret="your_client_secret" \   --project "your_project_id"
Or programmatically:
Copy code
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:
Copy code
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:
Copy code
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:
Copy code
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.
b
@chilly-king-10285 how to programatically get the auth code?
b
A message from kapa.ai
To programmatically get an authorization code in Ory's OAuth2 implementation, you need to initiate the Authorization Code flow by redirecting the user to the authorization endpoint. The authorization code is then returned to your redirect URI after the user authenticates and consents. Here's how to programmatically initiate the flow to get an authorization code: ## 1. Construct the Authorization URL
Copy code
javascript 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):
Copy code
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:
Copy code
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:
Copy code
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:
Copy code
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.