> ## Documentation Index
> Fetch the complete documentation index at: https://auth0.com/llms.txt
> Use this file to discover all available pages before exploring further.

> Learn how to get Access Tokens to make scheduled frequent calls to the Management API.

# Get Management API Access Tokens for Production

export const AuthCodeGroup = ({children, dropdown}) => {
  const [processedChildren, setProcessedChildren] = useState(children);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      unsubscribe = window.autorun(() => {
        const processChildren = node => {
          if (typeof node === "string") {
            let processedNode = node;
            for (const [key, value] of window.rootStore.variableStore.values.entries()) {
              const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
              processedNode = processedNode.replaceAll(new RegExp(escapedKey, "g"), value);
            }
            return processedNode;
          } else if (Array.isArray(node)) {
            return node.map(processChildren);
          } else if (node && node.props && node.props.children) {
            return {
              ...node,
              props: {
                ...node.props,
                children: processChildren(node.props.children)
              }
            };
          }
          return node;
        };
        setProcessedChildren(processChildren(children));
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  return <CodeGroup dropdown={dropdown}>{processedChildren}</CodeGroup>;
};

export const AuthCodeBlock = ({filename, icon, language, highlight, children}) => {
  const [displayText, setDisplayText] = useState(children);
  const [copyText, setCopyText] = useState(children);
  const wrapperRef = React.useRef(null);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      if (!window.autorun || !window.rootStore) {
        return;
      }
      unsubscribe = window.autorun(() => {
        let processedChildrenForDisplay = children;
        let processedChildrenForCopy = children;
        for (const [key, value] of window.rootStore.variableStore.values.entries()) {
          const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
          let displayValue = value;
          if (key === "{yourClientSecret}" && value !== "{yourClientSecret}") {
            displayValue = value.substring(0, 3) + "*****MASKED*****";
          }
          processedChildrenForDisplay = processedChildrenForDisplay.replaceAll(new RegExp(escapedKey, "g"), displayValue);
          processedChildrenForCopy = processedChildrenForCopy.replaceAll(new RegExp(escapedKey, "g"), value);
        }
        setDisplayText(processedChildrenForDisplay);
        setCopyText(processedChildrenForCopy);
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  useEffect(() => {
    if (!wrapperRef.current) return;
    const originalWriteText = navigator.clipboard.writeText.bind(navigator.clipboard);
    let isOverriding = false;
    const handleClick = e => {
      const button = e.target.closest('[data-testid="copy-code-button"]');
      if (!button || !wrapperRef.current.contains(button)) return;
      isOverriding = true;
      navigator.clipboard.writeText = text => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
          return originalWriteText(copyText);
        }
        return originalWriteText(text);
      };
      setTimeout(() => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
        }
      }, 100);
    };
    const wrapper = wrapperRef.current;
    wrapper.addEventListener('click', handleClick, true);
    return () => {
      wrapper.removeEventListener('click', handleClick, true);
      if (navigator.clipboard.writeText !== originalWriteText) {
        navigator.clipboard.writeText = originalWriteText;
      }
    };
  }, [copyText]);
  return <div ref={wrapperRef}>
      <CodeBlock filename={filename} icon={icon} language={language} lines highlight={highlight}>
        {displayText}
      </CodeBlock>
    </div>;
};

To make scheduled frequent calls for a production environment, you have to build a process at your backend that will provide you with a token automatically (and thus simulate a non-expiring token).

## Prerequisites

* [Register Machine-to-Machine Applications](/docs/get-started/auth0-overview/create-applications/machine-to-machine-apps).

## Get access tokens

To ask Auth0 for a <Tooltip tip="Management API: A product to allow customers to perform administrative tasks." cta="View Glossary" href="/docs/glossary?term=Management+API">Management API</Tooltip> v2 token, perform a `POST` operation to the `https://{yourDomain}/oauth/token` endpoint, using the credentials of the Machine-to-Machine Application you created in the prerequisite step.

The payload should be in the following format:

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request POST \
    --url 'https://{yourDomain}/oauth/token' \
    --header 'content-type: application/x-www-form-urlencoded' \
    --data grant_type=client_credentials \
    --data 'client_id={yourClientId}' \
    --data 'client_secret={yourClientSecret}' \
    --data 'audience=https://{yourDomain}/api/v2/'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/oauth/token");
  var request = new RestRequest(Method.POST);
  request.AddHeader("content-type", "application/x-www-form-urlencoded");
  request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2F{yourDomain}%2Fapi%2Fv2%2F", ParameterType.RequestBody);
  IRestResponse response = client.Execute(request);
  ```

  ```go Go theme={null}
  package main

  import (
  	"fmt"
  	"strings"
  	"net/http"
  	"io/ioutil"
  )

  func main() {

  	url := "https://{yourDomain}/oauth/token"

  	payload := strings.NewReader("grant_type=client_credentials&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2F{yourDomain}%2Fapi%2Fv2%2F")

  	req, _ := http.NewRequest("POST", url, payload)

  	req.Header.Add("content-type", "application/x-www-form-urlencoded")

  	res, _ := http.DefaultClient.Do(req)

  	defer res.Body.Close()
  	body, _ := ioutil.ReadAll(res.Body)

  	fmt.Println(res)
  	fmt.Println(string(body))

  }
  ```

  ```java Java theme={null}
  HttpResponse<String> response = Unirest.post("https://{yourDomain}/oauth/token")
    .header("content-type", "application/x-www-form-urlencoded")
    .body("grant_type=client_credentials&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2F{yourDomain}%2Fapi%2Fv2%2F")
    .asString();
  ```

  ```javascript Node.JS theme={null}
  var axios = require("axios").default;

  var options = {
    method: 'POST',
    url: 'https://{yourDomain}/oauth/token',
    headers: {'content-type': 'application/x-www-form-urlencoded'},
    data: new URLSearchParams({
      grant_type: 'client_credentials',
      client_id: '{yourClientId}',
      client_secret: '{yourClientSecret}',
      audience: 'https://{yourDomain}/api/v2/'
    })
  };

  axios.request(options).then(function (response) {
    console.log(response.data);
  }).catch(function (error) {
    console.error(error);
  });
  ```

  ```php PHP theme={null}
  $curl = curl_init();

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://{yourDomain}/oauth/token",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "grant_type=client_credentials&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2F{yourDomain}%2Fapi%2Fv2%2F",
    CURLOPT_HTTPHEADER => [
      "content-type: application/x-www-form-urlencoded"
    ],
  ]);

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    echo $response;
  }
  ```

  ```python Python theme={null}
  import http.client

  conn = http.client.HTTPSConnection("")

  payload = "grant_type=client_credentials&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2F{yourDomain}%2Fapi%2Fv2%2F"

  headers = { 'content-type': "application/x-www-form-urlencoded" }

  conn.request("POST", "/{yourDomain}/oauth/token", payload, headers)

  res = conn.getresponse()
  data = res.read()

  print(data.decode("utf-8"))
  ```

  ```ruby Ruby theme={null}
  require 'uri'
  require 'net/http'
  require 'openssl'

  url = URI("https://{yourDomain}/oauth/token")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Post.new(url)
  request["content-type"] = 'application/x-www-form-urlencoded'
  request.body = "grant_type=client_credentials&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2F{yourDomain}%2Fapi%2Fv2%2F"

  response = http.request(request)
  puts response.read_body
  ```
</AuthCodeGroup>

Remember to update `` `{yourClientSecret}` `` with the <Tooltip tip="Client Secret: Secret used by a client (application) to authenticate with the Authorization Server; it should be known to only the client and the Authorization Server and must be sufficiently random to not be guessable." cta="View Glossary" href="/docs/glossary?term=client+secret">client secret</Tooltip> in the [Settings tab of your Application](https://manage.auth0.com/#/applications/\{yourClientId}/settings).

The request parameters are:

| Request Parameter  | Description                                                                                                                                                                                                                      |
| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **grant\_type**    | Denotes which [OAuth 2.0 flow](/docs/authenticate/protocols/oauth#grant-types) you want to run. For machine to machine communication use the value `client_credentials`.                                                         |
| **client\_id**     | This is the value of the **Client ID** field of the Machine-to-Machine Application you created. You can find it on the [Settings tab of your Application](https://manage.auth0.com/#/applications/\{yourClientId}/settings).     |
| **client\_secret** | This is the value of the **Client Secret** field of the Machine-to-Machine Application you created. You can find it at the [Settings tab of your Application](https://manage.auth0.com/#/applications/\{yourClientId}/settings). |
| **audience**       | This is the value of the **Identifier** field of the `Auth0 Management API`. You can find it at the [Settings tab of the API](https://manage.auth0.com/#/apis).                                                                  |

<Warning>
  Use the `update:client_grants` and `create:client_grants` scopes with only high-privileged applications, as they allow the client to grant further permissions to itself.
</Warning>

The response will contain a [signed JWT](/docs/secure/tokens/json-web-tokens), an expiration time, the scopes granted, and the token type.

```json lines theme={null}
{
  "access_token": "eyJ...Ggg",
  "expires_in": 86400,
  "scope": "read:clients create:clients read:client_keys",
  "token_type": "Bearer"
}
```

From the above, we can see that our <Tooltip tip="Access Token: Authorization credential, in the form of an opaque string or JWT, used to access an API." cta="View Glossary" href="/docs/glossary?term=Access+Token">Access Token</Tooltip> will expire in 24 hours (86400 seconds), it has been authorized to read and create applications, and it is a [Bearer Access Token](https://tools.ietf.org/html/rfc6750).

### Use Auth0's Node.js client library

As an alternative to making HTTP calls, you can use the [node-auth0](https://www.npmjs.com/package/auth0) library to automatically [obtain tokens for the Management API](https://www.npmjs.com/package/auth0#user-content-management-api-client).

## Use access tokens

To use this token, include it in the `Authorization` header of your request.

<AuthCodeGroup>
  ```bash cURL lines theme={null}
  curl --request POST \
    --url http:///%7BmgmtApiEndpoint%7D \
    --header 'authorization: Bearer {yourMgmtApiAccessToken}' \
    --header 'content-type: application/json'
  ```

  ```csharp C# lines theme={null}
  var client = new RestClient("http:///%7BmgmtApiEndpoint%7D");
  var request = new RestRequest(Method.POST);
  request.AddHeader("content-type", "application/json");
  request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}");
  IRestResponse response = client.Execute(request);
  ```

  ```go Go lines expandable theme={null}
  package main

  import (
  	"fmt"
  	"net/http"
  	"io/ioutil"
  )

  func main() {

  	url := "http:///%7BmgmtApiEndpoint%7D"

  	req, _ := http.NewRequest("POST", url, nil)

  	req.Header.Add("content-type", "application/json")
  	req.Header.Add("authorization", "Bearer {yourMgmtApiAccessToken}")

  	res, _ := http.DefaultClient.Do(req)

  	defer res.Body.Close()
  	body, _ := ioutil.ReadAll(res.Body)

  	fmt.Println(res)
  	fmt.Println(string(body))

  }
  ```

  ```java Java lines theme={null}
  HttpResponse<String> response = Unirest.post("http:///%7BmgmtApiEndpoint%7D")
    .header("content-type", "application/json")
    .header("authorization", "Bearer {yourMgmtApiAccessToken}")
    .asString();
  ```

  ```javascript Node.JS lines theme={null}
  var axios = require("axios").default;

  var options = {
    method: 'POST',
    url: 'http:///%7BmgmtApiEndpoint%7D',
    headers: {
      'content-type': 'application/json',
      authorization: 'Bearer {yourMgmtApiAccessToken}'
    }
  };

  axios.request(options).then(function (response) {
    console.log(response.data);
  }).catch(function (error) {
    console.error(error);
  });
  ```

  ```php PHP lines expandable theme={null}
  $curl = curl_init();

  curl_setopt_array($curl, [
    CURLOPT_URL => "http:///%7BmgmtApiEndpoint%7D",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_HTTPHEADER => [
      "authorization: Bearer {yourMgmtApiAccessToken}",
      "content-type: application/json"
    ],
  ]);

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    echo $response;
  }
  ```

  ```python Python lines theme={null}
  import http.client

  conn = http.client.HTTPConnection("")

  headers = {
      'content-type': "application/json",
      'authorization': "Bearer {yourMgmtApiAccessToken}"
      }

  conn.request("POST", "%7BmgmtApiEndpoint%7D", headers=headers)

  res = conn.getresponse()
  data = res.read()

  print(data.decode("utf-8"))
  ```

  ```ruby Ruby lines theme={null}
  require 'uri'
  require 'net/http'

  url = URI("http:///%7BmgmtApiEndpoint%7D")

  http = Net::HTTP.new(url.host, url.port)

  request = Net::HTTP::Post.new(url)
  request["content-type"] = 'application/json'
  request["authorization"] = 'Bearer {yourMgmtApiAccessToken}'

  response = http.request(request)
  puts response.read_body
  ```
</AuthCodeGroup>

For example, in order to [Get all applications](https://auth0.com/docs/api/management/v2#!/Clients/get_clients) use the following:

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request GET \
    --url 'https://{yourDomain}/api/v2/clients' \
    --header 'authorization: Bearer {yourAccessToken}' \
    --header 'content-type: application/json'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/api/v2/clients");
  var request = new RestRequest(Method.GET);
  request.AddHeader("content-type", "application/json");
  request.AddHeader("authorization", "Bearer {yourAccessToken}");
  IRestResponse response = client.Execute(request);
  ```

  ```go Go theme={null}
  package main

  import (
  	"fmt"
  	"net/http"
  	"io/ioutil"
  )

  func main() {

  	url := "https://{yourDomain}/api/v2/clients"

  	req, _ := http.NewRequest("GET", url, nil)

  	req.Header.Add("content-type", "application/json")
  	req.Header.Add("authorization", "Bearer {yourAccessToken}")

  	res, _ := http.DefaultClient.Do(req)

  	defer res.Body.Close()
  	body, _ := ioutil.ReadAll(res.Body)

  	fmt.Println(res)
  	fmt.Println(string(body))

  }
  ```

  ```java Java theme={null}
  HttpResponse<String> response = Unirest.get("https://{yourDomain}/api/v2/clients")
    .header("content-type", "application/json")
    .header("authorization", "Bearer {yourAccessToken}")
    .asString();
  ```

  ```javascript Node.JS theme={null}
  var axios = require("axios").default;

  var options = {
    method: 'GET',
    url: 'https://{yourDomain}/api/v2/clients',
    headers: {'content-type': 'application/json', authorization: 'Bearer {yourAccessToken}'}
  };

  axios.request(options).then(function (response) {
    console.log(response.data);
  }).catch(function (error) {
    console.error(error);
  });
  ```

  ```php PHP theme={null}
  $curl = curl_init();

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://{yourDomain}/api/v2/clients",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => [
      "authorization: Bearer {yourAccessToken}",
      "content-type: application/json"
    ],
  ]);

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    echo $response;
  }
  ```

  ```python Python theme={null}
  import http.client

  conn = http.client.HTTPSConnection("")

  headers = {
      'content-type': "application/json",
      'authorization': "Bearer {yourAccessToken}"
      }

  conn.request("GET", "/{yourDomain}/api/v2/clients", headers=headers)

  res = conn.getresponse()
  data = res.read()

  print(data.decode("utf-8"))
  ```

  ```ruby Ruby theme={null}
  require 'uri'
  require 'net/http'
  require 'openssl'

  url = URI("https://{yourDomain}/api/v2/clients")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Get.new(url)
  request["content-type"] = 'application/json'
  request["authorization"] = 'Bearer {yourAccessToken}'

  response = http.request(request)
  puts response.read_body
  ```
</AuthCodeGroup>

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  You can get the curl command for each endpoint from the Management API v2 Explorer. Go to the endpoint you want to call, and click the **get curl command** link at the **Test this endpoint** section.
</Callout>

## Example: Python implementation

This python script gets a Management API v2 Access Token, uses it to call the [Get all applications](https://auth0.com/docs/api/management/v2#!/Clients/get_clients) endpoint, and prints the response in the console.

Before you run it make sure that the following variables hold valid values:

* `AUDIENCE`: The **Identifier** of the `Auth0 Management API`. You can find it at the [Settings tab of the API](https://manage.auth0.com/#/apis).
* `DOMAIN`: The **Domain** of the Machine-to-Machine Application you created.
* `CLIENT_ID`: The **<Tooltip tip="Client ID: Identification value given to your registered resource from Auth0." cta="View Glossary" href="/docs/glossary?term=Client+ID">Client ID</Tooltip>** of the Machine to Machine Application you created.
* `CLIENT_SECRET`: The **Client Secret** of the Machine-to-Machine Application you created.

```python lines expandable theme={null}
def main():
  import json, requests
  from requests.exceptions import RequestException, HTTPError, URLRequired

  # Configuration Values
  domain = 'YOUR_DOMAIN'
  audience = f'https://{domain}/api/v2/'
  client_id = '{yourClientId}'
  client_secret = '{yourClientSecret}'
  grant_type = "client_credentials" # OAuth 2.0 flow to use

  # Get an Access Token from Auth0
  base_url = f"https://{domain}"
  payload =  { 
    'grant_type': grant_type,
    'client_id': client_id,
    'client_secret': client_secret,
    'audience': audience
  }
  response = requests.post(f'{base_url}/oauth/token', data=payload)
  oauth = response.json()
  access_token = oauth.get('access_token')

  # Add the token to the Authorization header of the request
  headers = {
    'Authorization': f'Bearer {access_token}',
    'Content-Type': 'application/json'
  }

  # Get all Applications using the token
  try:
    res = requests.get(f'{base_url}/api/v2/clients', headers=headers)
    print(res.json())
  except HTTPError as e:
    print(f'HTTPError: {str(e.code)} {str(e.reason)}')
  except URLRequired as e:
    print(f'URLRequired: {str(e.reason)}')
  except RequestException as e:
    print(f'RequestException: {e}')
  except Exception as e:
    print(f'Generic Exception: {e}')

# Standard boilerplate to call the main() function.
if __name__ == '__main__':
  main()
```

## Learn more

* [Get Management API Access Tokens for Testing](/docs/secure/tokens/access-tokens/management-api-access-tokens/get-management-api-access-tokens-for-testing)
* [Get Management API Access Tokens for Single-Page Applications](/docs/secure/tokens/access-tokens/management-api-access-tokens/get-management-api-tokens-for-single-page-applications)
* [Applications in Auth0](/docs/get-started/applications)
