Rayrun
← Back to Discord Forum

Setting Bearer token for every request

Hello, I have a REST API that requires to set a JWT token on every request as Bearer token. So I first need to authenticate and get the token using a POST request, and then set it on ecery subsequent call. How do I do this in Playwright? The docs haven an exemple using a static token https://playwright.dev/docs/api-testing#configuration. The issue with this is that it is always the same token. I have to request a new token with each run of my tests. I tried using an auth.setup.ts:

import { test as setup } from '@playwright/test';

setup('authenticate', async ({ request }) => {
  // Perform authentication steps. Replace these actions with your own.
  const authResult = await request.post('http://localhost:8080/auth/realms/somerealm/protocol/openid-connect/token', {
    form: {
        clientId: 'blah',
        grant_type: 'client_credentials',
        client_secret: 'verysecret',
        audience: 'http://localhost:8081/'
    }
  });
  
  // End of authentication steps.
  const data = await authResult.json();
  process.env.BEARER_TOKEN = data.access_token;
});

Then I try adding it as a dependency like this:

projects: [
    // Setup project
    // Deals with authentication
    { name: 'setup', testMatch: /.*\.setup\.ts/ },

    {
      name: 'chromium',
      use: { 
        ...devices['Desktop Chrome'],
        /* Add Authorization to all requests */
        extraHTTPHeaders: {
          // We set this header per GitHub guidelines.
          'Accept': 'application/vnd.github.v3+json',
          // Add authorization token to all requests.
          // Assuming personal access token available in the environment.
          'Authorization': `Bearer ${process.env.BEARER_TOKEN}`,
        },
      },
      dependencies: ['setup'],
    },

But that doesn't work, my requests are not authenticated. Am I doing something wrong? Is there a better way?

This thread is trying to answer question "How to set a JWT token as Bearer token for every request in Playwright?"

4 replies

I would also like to know the answer to this question

@roux.ant: Your configuration is set before the setup function. Env variable will be empty. I think you can write a Fixture for this

Your configuration is set before the setup function. Env variable will be empty. I think you can write a Fixture for this

@jan.ostgren: Yes, I ended up using a fixture :o)

Yes, I ended up using a fixture :o)

Thanks a lot for the answer

Related Discord Threads

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.