Test Basic Authentication in API by Playwright

 

Basic Authentication involves sending a username and password in the request header, encoded in Base64 format.

Playwright provides a way to configure this using browser.newContext() with httpCredentials.


Steps:

  • Set up Playwright.
  • Create a new browser context with HTTP credentials.
  • Navigate to a website that requires basic authentication.
  • Assert the successful authentication.

We’ll use the public website:
https://httpbin.org/basic-auth/user/passwd


It requires basic auth with:

  • Username: user

  • Password: passwd




Playwright Java Code Example:


import com.microsoft.playwright.*;

public class BasicAuthTest {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            // Create a browser
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

            // Set up HTTP Basic Auth credentials
            Browser.NewContextOptions contextOptions = new Browser.NewContextOptions()
                    .setHttpCredentials("user", "passwd");  // username: user, password: passwd

            // Create browser context with credentials
            BrowserContext context = browser.newContext(contextOptions);

            // Open a new page
            Page page = context.newPage();

            // Navigate to the Basic Auth test URL
            page.navigate("https://httpbin.org/basic-auth/user/passwd");

            // Verify if authentication is successful
            String bodyText = page.textContent("body");
            if (bodyText.contains("\"authenticated\": true")) {
                System.out.println("Basic authentication successful!");
            } else {
                System.out.println("Basic authentication failed.");
            }

            // Close browser
            browser.close();
        }
    }
}




Output:

Basic authentication successful!





Maven Dependencies:


<dependency>
  <groupId>com.microsoft.playwright</groupId>
  <artifactId>playwright</artifactId>
  <version>1.44.0</version>
</dependency>


No comments:

Post a Comment