# Get the correct Access Token for Automated Tests

**URL:** <https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532>\
**Category:** Get Help\
**Tags:** apis, application\
**Created:** [May 6, 2024, 10:34pm UTC](https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532 "2024-05-06T22:34:09Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![jaime1](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@jaime1](https://community.auth0.com/u/jaime1)\
**Post date:** [May 6, 2024, 10:34pm UTC](https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532/1 "2024-05-06T22:34:09Z")

</div>

Hi All,  
So I want to create integration tests via Node.js to run locally on my machine and eventually use in an automated pipeline.

We have a Test application `(Test Application) Machine to Machine` and in the Quick Start, there is an example to get the access token and then use the access token against our APIs.

I have tried the example against both `Auth0 Management API` and our Dev application.  
Both times, the first request returns an access token but when I try the access token against our API the Node.js Express application returns a 400 error.

```auto
{
  statusCode: 400,
  error: 'Bad Request',
  message: "Object didn't pass validation for format user-id: XXX@clients",
  errorCode: 'invalid_uri'
}

```

the User Id doesn’t have `auth0|XXX` but `XXX@clients`, I am not sure if that is the issue or not.

Surely the quick start guide should work so I presume I am missing some Auth0 configuration in the Test application?

Please help.

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [May 6, 2024, 11:50pm UTC](https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532/3 "2024-05-06T23:50:45Z")

</div>

Hey there @jaime1 welcome to the community!

Do you mind sharing the specific quick start you are working off of?

> [@jaime1](#):
>
> the User Id doesn’t have `auth0|XXX` but `XXX@clients`, I am not sure if that is the issue or not.

It’s hard to know without looking at the example, but this error does lead me to believe there’s a simple mismatch in what the API is expected and what you’re passing.

Let us know!

---

<div class="post-metadata">

**Author:** ![jaime1](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@jaime1](https://community.auth0.com/u/jaime1)\
**Post date:** [May 7, 2024, 9:51am UTC](https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532/4 "2024-05-07T09:51:22Z")

</div>

Hi!

I am working from here: [https://manage.auth0.com/dashboard/us/dev-l2swae8to1esqjyb/applications/3J3pD3kBvPwTMapnLDPZTdM2HyFsKRYr/quickstart](https://manage.auth0.com/dashboard/us/dev-l2swae8to1esqjyb/applications/3J3pD3kBvPwTMapnLDPZTdM2HyFsKRYr/quickstart)

Does that help? Can you access that URL?

```auto
Mytaverse Dev (Test Application)
Machine to Machine

Client ID

3J3pD3kBvPwTMapnLDPZTdM2HyFsKRYr

```

---

<div class="post-metadata">

**Author:** ![jaime1](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@jaime1](https://community.auth0.com/u/jaime1)\
**Post date:** [May 8, 2024, 9:19am UTC](https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532/5 "2024-05-08T09:19:15Z")

</div>

Hi,

Any help?  
@ty.frith ?

Thanks

---

<div class="post-metadata">

**Author:** ![jaime1](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@jaime1](https://community.auth0.com/u/jaime1)\
**Post date:** [May 9, 2024, 2:16pm UTC](https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532/6 "2024-05-09T14:16:41Z")

</div>

Hi,

Can someone please respond 🙂

Thanks

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [May 9, 2024, 6:33pm UTC](https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532/7 "2024-05-09T18:33:22Z")

</div>

Hey there @jaime1!

The `quickstart` section in the m2m application unfortunately doesn’t give me much info - What does the API look like that you are validating the access token against? I just tested a quick Node sample API (below) and the token I received from the quickstart section for my API was validated successfully, allowing me to access the `/api/private` endpoint.

```auto
require('dotenv').config();
const express = require('express');
const { auth } = require('express-oauth2-jwt-bearer');

const app = express();
const port = process.env.PORT || 3000;

// Auth0 JWT validation middleware configuration
const checkJwt = auth({
  audience: process.env.AUDIENCE,
  issuerBaseURL: process.env.DOMAIN,
});

// A protected route that requires a valid JWT
app.get('/api/private', checkJwt, (req, res) => {
  res.status(200).send('Access granted to protected data');
});

// Error handler for unauthorized access
app.use((err, req, res, next) => {
  if (err.name === 'UnauthorizedError') {
    return res.status(401).send('Invalid token');
  }
  next(err);
});

// Start the server
app.listen(port, () => {
  console.log(`Server listening on http://localhost:${port}`);
});

```

---

<div class="post-metadata">

**Author:** ![jaime1](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@jaime1](https://community.auth0.com/u/jaime1)\
**Post date:** [May 9, 2024, 9:05pm UTC](https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532/8 "2024-05-09T21:05:42Z")

</div>

Hi,

So in the integration test, we get the token by doing:

```auto
const response = await axios.post(
    `https://${AUTH0_DOMAIN}/oauth/token`,
    {
      client_id: '3J3pD3kBvPwTMapnLDPZTdM2HyFsKRYr',
      client_secret:
        'XXX',
      audience: 'Mytaverse:Dev',
      grant_type: 'client_credentials',
    },
    { headers: { 'content-type': 'application/json' } },
  );

```

We then use the token to our API. In the API, we have a middleware for auth that we do:

```auto
const getKey = (header: any, callback: any) => {
        console.log('header.kid', header.kid);
        jwksRSAClient.getSigningKey(header.kid, (err: any, key: any) => {
          const signingKey = key.publicKey || key.rsaPublicKey;

          callback(null, signingKey);
        });
      };

      token = token.replace('Bearer ', '');

      jwt.verify(token, getKey, function (err: any, decoded: any) {

```

This passes OK.

The decoded object returns:

```auto
decoded {
  iss: 'XXX',
  sub: '3J3pD3kBvPwTMapnLDPZTdM2HyFsKRYr@clients',
  aud: 'Mytaverse:Dev',
  iat: 1715288184,
  exp: 1715291784,
  scope: 'ALL OK',
  gty: 'client-credentials',
  azp: '3J3pD3kBvPwTMapnLDPZTdM2HyFsKRYr'
}

```

We check to see if this user exists in our DB `3J3pD3kBvPwTMapnLDPZTdM2HyFsKRYr@clients`  
and it doesn’t so then we then get the M2M token by calling:

```auto
const data = await axios.post(`https://${AUTH0_DOMAIN}/oauth/token`, {
      client_id: AUTH0_M2M_API_CLIENT_ID,
      client_secret: AUTH0_M2M_API_CLIENT_SECRET,
      audience: AUTH0_M2M_API_AUDIENCE,
      grant_type: 'client_credentials',
    });

```

We then call Auth0 using the M2M token:

```auto
`https://${AUTH0_DOMAIN}/api/v2/users/${userId}`

```

And this produces the error:

```auto
{
  statusCode: 400,
  error: 'Bad Request',
  message: "Object didn't pass validation for format user-id: 3J3pD3kBvPwTMapnLDPZTdM2HyFsKRYr@clients",
  errorCode: 'invalid_uri'
}

```

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [May 9, 2024, 10:13pm UTC](https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532/9 "2024-05-09T22:13:09Z")

</div>

Awesome, thanks for the additional detail!

> [@jaime1](#):
>
> We check to see if this user exists in our DB `3J3pD3kBvPwTMapnLDPZTdM2HyFsKRYr@clients`  
> and it doesn’t so then we then get the M2M token by calling:

I’m a bit confused by this step - The `sub` claim here is that of a M2M app and not a user.

> [@jaime1](#):
>
> We then call Auth0 using the M2M token:
> 
> ```auto
> `https://${AUTH0_DOMAIN}/api/v2/users/${userId}`
> 
> ```

If you are passing a `{userID}` that looks like `3J3pD3kBvPwTMapnLDPZTdM2HyFsKRYr@clients` this won’t work. A user\_id should look like `{identity provider id}|{unique id in the provider}` or `facebook|1234567890, auth0|123456, etc.`

---

<div class="post-metadata">

**Author:** ![jaime1](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@jaime1](https://community.auth0.com/u/jaime1)\
**Post date:** [May 9, 2024, 10:21pm UTC](https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532/10 "2024-05-09T22:21:15Z")

</div>

Hi,

Yes, that is what I don’t understand, the first call:

```auto
const response = await axios.post(
    `https://${AUTH0_DOMAIN}/oauth/token`,
    {
      client_id: '3J3pD3kBvPwTMapnLDPZTdM2HyFsKRYr',
      client_secret:
        'XXX',
      audience: 'Mytaverse:Dev',
      grant_type: 'client_credentials',
    },
    { headers: { 'content-type': 'application/json' } },
  );

```

This gives me `sub: ‘3J3pD3kBvPwTMapnLDPZTdM2HyFsKRYr@clients’,

Which is wrong no? It should be `auth0|XXX` like my first post stated?  
Do I need to create a test user for ` Mytaverse Dev (Test Application)`?  
I thought that the application was a User in itself for testing?

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [May 9, 2024, 10:31pm UTC](https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532/11 "2024-05-09T22:31:58Z")

</div>

OK I think I understand!

The first call is just performing a [client credentials exchange](https://auth0.com/docs/get-started/authentication-and-authorization-flow/client-credentials-flow) and getting you an m2m access token, no user involved at all.

> [@jaime1](#):
>
> Do I need to create a test user for ` Mytaverse Dev (Test Application)`?  
> I thought that the application was a User in itself for testing?

Creating a test user seems to make sense for what you’re doing. Once you create one, you can get this user’s access token using the [resource owner password flow](https://auth0.com/docs/get-started/authentication-and-authorization-flow/resource-owner-password-flow) (fine for testing). So instead of using the client’s credentials, you’ll use the user’s credentials against the `/oauth/token` [endpoint](https://auth0.com/docs/api/authentication#resource-owner-password-flow).

---

<div class="post-metadata">

**Author:** ![jaime1](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@jaime1](https://community.auth0.com/u/jaime1)\
**Post date:** [May 9, 2024, 10:36pm UTC](https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532/12 "2024-05-09T22:36:00Z")

</div>

OK perfect, I shall do that.

Is there a way to create the Test User for my app via the Browser/UI or do I have to do it via the API?

Thanks!

---

<div class="post-metadata">

**Author:** ![jaime1](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@jaime1](https://community.auth0.com/u/jaime1)\
**Post date:** [May 9, 2024, 10:40pm UTC](https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532/13 "2024-05-09T22:40:18Z")

</div>

No worries, I found it

---

<div class="post-metadata">

**Author:** ![jaime1](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@jaime1](https://community.auth0.com/u/jaime1)\
**Post date:** [May 9, 2024, 11:21pm UTC](https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532/14 "2024-05-09T23:21:37Z")

</div>

Thank you for the help that worked.  
Thanks.

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [May 9, 2024, 11:22pm UTC](https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532/15 "2024-05-09T23:22:04Z")

</div>

Awesome! Thanks for confirming and happy to help 🙂

---

<div class="post-metadata">

**Author:** ![ronak](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ronak/32/48755_2.png) [@ronak](https://community.auth0.com/u/ronak)\
**Post date:** [May 22, 2024, 5:31pm UTC](https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532/16 "2024-05-22T17:31:13Z")

</div>

Does auth0 tenant make use of organizations?

---

<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:** [June 5, 2024, 5:31pm UTC](https://community.auth0.com/t/get-the-correct-access-token-for-automated-tests/133532/17 "2024-06-05T17:31:13Z")

</div>

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