Call Admin routes with API key

So, I created a System user of role admin and then created an API key like this:

 const apiKey = await auth.api.createApiKey({
        body: {
          name: 'System',
          userId: '01991763-29cc-7409-9136-98d127723df9',
          rateLimitEnabled: false,
          permissions: {
            user: ['create','list','set-role','ban','impersonate','delete','set-password'],
            session: ['list', 'revoke', 'delete'],
          },
        },
      });



When trying to use the returned API Key to call the setUserPassword or listUsers I get this error:
{
  "type": "Error",
  "message": "",
  "stack": "APIError",
  "status": "UNAUTHORIZED",
  "headers": {},
  "statusCode": 401,
   "name": "APIError"
}


Here is the example of how its being called:

    const data = await auth.api
      .setUserPassword({
        body: {
          newPassword,
          userId: user.userId,
        },
        headers: new Headers({
          'x-api-key': env.BETTER_AUTH_SYSTEM_KEY,
        }),
      });

    const list = await auth.api
      .listUsers({
        headers: new Headers({
          'x-api-key': <apiKey>,
        }),
        query: {},
      });


I've tried getting a session from the API Key and it does work

    const session = await auth.api
      .getSession({
        headers: new Headers({
          'x-api-key': <apiKey>,
        }),
      })
{
  "user": {
    "username": "system",
    "role": "admin",
    "id": "01991763-29cc-7409-9136-98d127723df9"
    ...
  },
  "session": {
    "userId": "01991763-29cc-7409-9136-98d127723df9",
    ...
  }
}

But this does fail
    const permissionsCheck = await auth.api
      .userHasPermission({
        body: {
          permission: {
            user: ['set-password', 'list'],
          },
        },
        headers: new Headers({
          'x-api-key': <apiKey>,
        }),
      })
Was this page helpful?