Search code examples
playwright

Can Playwright handle OAUTH 2.0 logons that use redirects


I am trying figure out how to use playwright to logon to our web application and get an access token that provides access to web services. It uses oauth 2.0 redirects with grant type Authorization Code Flow with PKCE. The response content isn't available after the final user/password logon. Webdriver works fine and has the access token available after user/password logon. I'm trying to replicate the same process in Playwright.


Solution

  • From what I understand, you are asking if Playwright can be used to login to an application using OAuth, which obviously has redirects happening.

    Official docs about Playwright authentication: https://playwright.dev/docs/auth

    Example OAuth login that works just fine:

    test.describe('Login with OAuth', () => {
      test("login, save cookies and localStorage", async ({ page, context }) => {
          // Navigate to application login page
          await page.goto('https://loginwithoauth.com');
    
          // Log in by clicking the OAuth button
          await page.locator('text=OAuth login').click();
    
          // Now we are moving to a 3rd party login page....
    
          // We are at a new page for login, type email address
          await page.click('[placeholder="Email Address"]');
          await page.locator('[placeholder="Email Address"]').fill('username...');
          await page.click('[placeholder="Password"]');
          await page.locator('[placeholder="Password"]').fill('password...');
          await page.locator('button:has-text("Sign in")').click();
          
          // Now we're back to our own app
          // Wait that the main page has loaded
          await page.waitForURL('**/home', { timeout: 10000 });
    
          // Wait for network to be idle, if we save storage too early, needed storage values might not yet be available
          await page.waitForLoadState('networkidle');
    
          // Save cookies and localstorage to a file, which we can use later in the tests to be logged in automatically
          await context.storageState({ path: 'state.json' });
          console.log('Cookies and localStorage should now be saved in state.json file for further cache usage...');
      });
      // Test suite ends
    });