# How get a access token in m2m actions?

**URL:** <https://community.auth0.com/t/how-get-a-access-token-in-m2m-actions/137929>\
**Category:** Get Help\
**Tags:** ticket-management, support-center\
**Created:** [July 2, 2024, 3:01pm UTC](https://community.auth0.com/t/how-get-a-access-token-in-m2m-actions/137929 "2024-07-02T15:01:38Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![pmoraga](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/pmoraga/32/49049_2.png) [@pmoraga](https://community.auth0.com/u/pmoraga)\
**Post date:** [July 2, 2024, 3:01pm UTC](https://community.auth0.com/t/how-get-a-access-token-in-m2m-actions/137929/1 "2024-07-02T15:01:38Z")

</div>

I was looking in previous questions but the answers did not work, my purpose is to get the access token in a m2m flow, I have seen in other answers that use " const newToken = await management.getAccessToken();" but it gives me error because getAccessToken does not exist in the class,

how can I access the machine’s access token in an action for an m2m flow?

Reference:

> [@Caching M2M token in Actions](https://community.auth0.com/t/caching-m2m-token-in-actions/123247):
>
> Hello, I was trying to implement M2M access token caching using the instructions provided in this post: In this example the token caching is done as a post login step, however for M2M caching I tried to implement inside the onExecuteCredentialsExchange, but when I tried out the code it got stuck in a loop and I quickly exceeded my monthly quota. I think the loop happens when I try to call the authClient.oauth.clientCredentialsGrant() function because it automatically counts as an on execute cr…

[https://community.auth0.com/t/caching-management-api-access-tokens-in-login-action/95855](https://community.auth0.com/t/caching-management-api-access-tokens-in-login-action/95855)

---

<div class="post-metadata">

**Author:** ![rueben.tiow](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/rueben.tiow/32/11646_2.png) [@rueben.tiow](https://community.auth0.com/u/rueben.tiow)\
**Post date:** [July 3, 2024, 7:34pm UTC](https://community.auth0.com/t/how-get-a-access-token-in-m2m-actions/137929/3 "2024-07-03T19:34:33Z")

</div>

Hi @pmoraga,

Welcome to the Auth0 Community!

I have just tested this on my end and was able to call the `await management.getAccessToken()` method successfully.

Have you made sure to include the required dependencies in your Action script? Specifically, the Auth0 NPM module?

Thanks,  
Rueben

---

<div class="post-metadata">

**Author:** ![pmoraga](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/pmoraga/32/49049_2.png) [@pmoraga](https://community.auth0.com/u/pmoraga)\
**Post date:** [July 3, 2024, 9:30pm UTC](https://community.auth0.com/t/how-get-a-access-token-in-m2m-actions/137929/4 "2024-07-03T21:30:27Z")

</div>

Hi Ruben, thank for you response, i actually use this version (in image)  
for other side, i have a cuestion for you ruben, in someones post of cummunity i saw what use api.cache.get(‘management-token’); for get token in cache, is correct that way?

 ![Captura de pantalla 2024-07-03 a la(s) 5.28.25 p. m.](https://global.discourse-cdn.com/auth0/original/3X/9/9/99be22eaf0500ea1656bf335b9060cc1474667df.png)

---

<div class="post-metadata">

**Author:** ![pmoraga](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/pmoraga/32/49049_2.png) [@pmoraga](https://community.auth0.com/u/pmoraga)\
**Post date:** [July 9, 2024, 3:26pm UTC](https://community.auth0.com/t/how-get-a-access-token-in-m2m-actions/137929/5 "2024-07-09T15:26:46Z")

</div>

I do downgrade the version of “auth0” to 3.7.2 and find the method getAccessToken, but i saw other solution your proposes and i take that code for test, but when i call the service give **error for timeout** , for other side is the same when i try connect with redis from auth0 action, its a capability of auth0 it can connect to extern service? or ¿i should do a config some?

 ![Captura de pantalla 2024-07-09 a la(s) 11.25.16 a. m.](https://global.discourse-cdn.com/auth0/original/3X/7/a/7ace2f44f331bee52c43a3ed9ef58e625013d181.png)

my code is:

```auto
exports.onExecuteCredentialsExchange = async (event, api) => {
      const ManagementClient = require('auth0').ManagementClient;
      const jwt_decode = require('jwt-decode');

      //get current value for 'my-api-token'
      const record = api.cache.get('management-token');
      console.log("Record: ", record);
      let token = record?.value;
      let current_time = Date.now().valueOf() / 1000;

      console.log("Cached token: ", token);
      if (token != undefined) {
        var decoded = jwt_decode(token);
      }

      //Check if cached token exists/is not undefined and not expired
      if (token != undefined && decoded.exp > current_time) {
        //Initialize management client with existing token to use against Management API
        const managementWithOldToken = new ManagementClient({
          token: token,
          domain: event.secrets.DOMAIN,
        });
      
      } 
      else if (token == undefined || decoded.exp < current_time) {
        //Initialize management client with credentials
        const management = new ManagementClient({
          domain: event.secrets.DOMAIN,
          clientId: event.request.body.client_id,
          clientSecret: event.request.body.client_secret,
          audience: event.request.body.audience,
          tokenProvider: {
            enableCache: true,
            cacheTTLInSeconds: 86400
          }
        });

        //Get new access token and set it in cache
        const newToken = await management.getAccessToken();
        api.cache.set('first',newToken.slice(0,2048))
        api.cache.set('second', newToken.slice(2048,4096))
        api.cache.set('third', newToken.slice(4096))   
        const getNewToken = api.cache.get('first').value + api.cache.get('second').value + api.cache.get('third').value
        //Initialize management client with new token to use against Management API
        const managementWithNewToken = new ManagementClient({
          token: getNewToken,
          domain: event.secrets.DOMAIN,
        });      
        console.log('token success' , getNewToken)
      }
}

```

i saw this example @rueben.tiow

> [@Caching M2M access token in Actions](https://community.auth0.com/t/caching-m2m-access-token-in-actions/100734/3):
>
> Hi @saiful1991, Welcome to the Auth0 Community! I have tested this myself and found that the Access Token value is too large, which is why you are experiencing the undefined error. This is consistent with our [Actions Limitations](https://auth0.com/docs/customize/actions/limitations#:~:text=Cache%20keys%20have%20a%20maximum%20size%20of%2064%20bytes%20and%20values%20have%20a%20maximum%20size%20of%202048%20bytes) documentation, which states that Cache keys have a maximum size of 64 bytes and values have a maximum size of 2048 bytes. Investigating further, I found that the Access Token is 4234 bytes which exceed the maximum size allowed for a value. I am going to look further…

---

<div class="post-metadata">

**Author:** ![mayank.jha](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@mayank.jha](https://community.auth0.com/u/mayank.jha)\
**Post date:** [August 29, 2024, 11:00am UTC](https://community.auth0.com/t/how-get-a-access-token-in-m2m-actions/137929/6 "2024-08-29T11:00:30Z")

</div>

I saw this example and the discussion for Caching the Access token with key. I am able to set the cache but while doing the next call again I not getting the cached data with same key.

my code  
const record = api.cache.get(‘my-api-token’);  
console.log(‘In function record’, record);  
let token = record?.value;  
let current\_time = Date.now().valueOf() / 1000;

```
if (token != undefined) {
var decoded = jwtDecode(token);
}
console.log('existing token', token);
console.log('decoded', decoded);
console.log('current_time', current_time);
if (token != undefined && decoded.exp > current_time) {
console.log('if condition');
const managementWithOldToken = new ManagementClient({
  token: token,
  domain: event.secrets.domain,
});
return token;
//Call Management API 
} else if (token == undefined || decoded.exp < current_time) {
    console.log('else if condition');
    //Initialize management client with credentials
    const management = new ManagementClient({
        domain: event.secrets.M2M_DOMAIN,
        clientId: event.secrets.M2M_CLIENT_ID,
        clientSecret: event.secrets.M2M_CLIENT_SECRET,
        audience: event.secrets.AUDIENCE,
        tokenProvider: {
            enableCache: true,
            cacheTTLInSeconds: 86400
        }
    });
    
    //Get new access token and set it in cache
    const newToken = await management.getAccessToken();
    console.log('newToken', newToken);
    console.log('newToken size', newToken?.size);
    // api.cache.set('first',newToken.slice(0,2048))
    // api.cache.set('second', newToken.slice(2048,4096))
    // api.cache.set('third', newToken.slice(4096))   
    // const getNewToken = api.cache.get('first').value + api.cache.get('second').value + api.cache.get('third').value
    
    // console.log('getNewToken', getNewToken);
     const result = api.cache.set('my-api-token', newToken);

```

---

<div class="post-metadata">

**Author:** ![rueben.tiow](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/rueben.tiow/32/11646_2.png) [@rueben.tiow](https://community.auth0.com/u/rueben.tiow)\
**Post date:** [January 3, 2025, 11:05pm UTC](https://community.auth0.com/t/how-get-a-access-token-in-m2m-actions/137929/7 "2025-01-03T23:05:12Z")

</div>

Hi @pmoraga,

> [@pmoraga](#):
>
> i saw what use api.cache.get(‘management-token’); for get token in cache, is correct that way?

Yes, that’s correct! The `api.cache.get(key)` is the correct method to get a cached item in an M2M action script. (Reference: [Actions Triggers: credentials-exchange - API Object](https://auth0.com/docs/customize/actions/explore-triggers/machine-to-machine-trigger/credentials-exchange-api-object#:~:text=in%20the%20cache.-,api.cache.get(key),-Retrieve%20a%20record)).

> [@pmoraga](#):
>
> I do downgrade the version of “auth0” to 3.7.2 and find the method getAccessToken, but i saw other solution your proposes and i take that code for test, but when i call the service give **error for timeout**

According to the `500` error code you experienced. it happens when your code takes more than 20 seconds to complete the action script. This is mentioned in our [Actions Limitations](https://auth0.com/docs/customize/actions/limitations#:~:text=Each%20execution%20of%20a%20flow%20must%20complete%20in%2020%20seconds%20or%20less%20or%20the%20processing%20will%20end%20in%20an%20error.%20Limiting%20HTTP%20requests%20is%20the%20best%20way%20to%20keep%20within%20this%20time%20limit.) documentation.

Additionally, I noticed you used the token already generated using the client credentials grant to initialize a new ManagementClient using the existing token. This is an unnecessary step since you already have a usable Management API token in your first request and can skip this step. This bit of code might be responsible for exceeding the execution time limit.

Lastly, I confirmed that Auth0 node version 3.7.2 is the last version that supports the `getAccessToken()` method. Newer versions do not support this method.

> [@mayank.jha](#):
>
> I saw this example and the discussion for Caching the Access token with key. I am able to set the cache but while doing the next call again I not getting the cached data with same key.

This behavior is expected since the cache item is not guaranteed for subsequent executions. It is only guarantees for all Actions in the same flow for a single execution reliably. This is mentioned in our [Cached Data limitations](https://auth0.com/docs/customize/actions/limitations#:~:text=The%20cache%20should%20be%20available%20for%20all%20Actions%20in%20the%20same%20flow%20for%20a%20single%20execution%20reliably%2C%20however%20for%20subsequent%20executions%20(such%20as%20a%20different%20flow%2C%20another%20user%20login%2C%20or%20a%20user%20returning%20from%20a%20redirect%20action)%20it%20is%20not%20guaranteed.) documentation.

Thanks,  
Rueben

---

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/auth0/original/3X/b/5/b560f266932fcce5d57f09a6595bd50518cae3f3.jpeg) [@system](https://community.auth0.com/u/system)\
**Post date:** [January 17, 2025, 11:05pm UTC](https://community.auth0.com/t/how-get-a-access-token-in-m2m-actions/137929/8 "2025-01-17T23:05:12Z")

</div>

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
