Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: update authentication guide to use storageState() api #4948

Merged
merged 1 commit into from Jan 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 7 additions & 8 deletions docs/examples/authentication.js
Expand Up @@ -3,13 +3,13 @@ const assert = require('assert');

/**
* In this script, we will login on GitHub.com through Chromium,
* and reuse the login cookies state inside WebKit. This recipe can be
* and reuse login state inside WebKit. This recipe can be
* used to speed up tests by logging in once and reusing login state.
*
* Steps summary
* 1. Login on GitHub.com in Chromium
* 2. Export cookies from Chromium browser context
* 3. Set cookies in WebKit browser context and verify login
* 2. Export storage state from Chromium browser context
* 3. Set storage state in WebKit browser context and verify login
*/

const account = { login: '', password: '' };
Expand All @@ -31,14 +31,13 @@ const account = { login: '', password: '' };
await crPage.click('input[type="submit"]');
await verifyIsLoggedIn(crPage);

// Get cookies from Chromium browser context
const cookies = await crContext.cookies();
// Get storage state from Chromium browser context
const storageState = await crContext.storageState();
await crBrowser.close();

// Create WebKit browser context and load cookies
// Create WebKit browser context with saved storage state
const wkBrowser = await webkit.launch();
const wkContext = await wkBrowser.newContext();
await wkContext.addCookies(cookies)
const wkContext = await wkBrowser.newContext({ storageState });

// Navigate to GitHub.com and verify that we are logged in
const wkPage = await wkContext.newPage();
Expand Down
114 changes: 26 additions & 88 deletions docs/src/auth.md
Expand Up @@ -69,114 +69,53 @@ existing authentication state in new browser contexts.
Web apps use cookie-based or token-based authentication, where authenticated
state is stored as [cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies)
or in [local storage](https://developer.mozilla.org/en-US/docs/Web/API/Storage).
The Playwright API can be used to retrieve this state from authenticated contexts
and then load it into new contexts.
Playwright provides [`method: Browser.storageState`] method that can be used to retrieve storage state from authenticated contexts and then create new contexts with prepopulated state.

Cookies and local storage state can be used across different browsers. They depend
on your application's authentication model: some apps might require both cookies
and local storage.

The following code snippets retrieve state from an authenticated page/context and
load them into a new context.

### Cookies
The following code snippet retrieves state from an authenticated context and
creates a new context with that state.

```js
// Get cookies and store as an env variable
const cookies = await context.cookies();
process.env.COOKIES = JSON.stringify(cookies);
// Save storage state and store as an env variable
const storage = await context.storageState();
process.env.STORAGE = JSON.stringify(storage);

// Set cookies in a new context
const deserializedCookies = JSON.parse(process.env.COOKIES)
await context.addCookies(deserializedCookies);
// Create a new context with the saved storage state
const storageState = JSON.parse(process.env.STORAGE);
const context = await browser.newContext({ storageState });
```

```python-async
import json
import os
# Get cookies and store as an env variable
cookies = await context.cookies()
os.environ["COOKIES"] = json.dumps(cookies)
# Save storage state and store as an env variable
storage = await context.storage_state()
os.environ["STORAGE"] = json.dumps(storage)

# Set cookies in a new context
deserialized_cookies = json.loads(os.environ["COOKIES"])
await context.add_cookies(deserialized_cookies)
# Create a new context with the saved storage state
storage_state = json.loads(os.environ["STORAGE"])
context = await browser.new_context(storage_state=storage_state)
```

```python-sync
import json
import os
# Get cookies and store as an env variable
cookies = context.cookies()
os.environ["COOKIES"] = json.dumps(cookies)

# Set cookies in a new context
deserialized_cookies = json.loads(os.environ["COOKIES"])
context.add_cookies(deserialized_cookies)
```

### Local storage
Local storage ([`window.localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage))
is specific to a particular domain.

```js
// Get local storage and store as env variable
const localStorage = await page.evaluate(() => JSON.stringify(window.localStorage));
process.env.LOCAL_STORAGE = localStorage;

// Set local storage in a new context
const localStorage = process.env.LOCAL_STORAGE;
await context.addInitScript(storage => {
if (window.location.hostname === 'example.com') {
const entries = JSON.parse(storage);
Object.keys(entries).forEach(key => {
window.localStorage.setItem(key, entries[key]);
});
}
}, localStorage);
```

```python-async
import os
import json
# Get local storage and store as env variable
local_storage = await page.evaluate("() => JSON.stringify(window.localStorage))
os.environ["LOCAL_STORAGE"] = local_storage

# Set local storage in a new context
local_storage = os.environ["LOCAL_STORAGE"]
await context.add_init_script("""storage => {
if (window.location.hostname == 'example.com') {
entries = JSON.parse(storage)
Object.keys(entries).forEach(key => {
window.localStorage.setItem(key, entries[key])
})
}
}""", local_storage)
```

```python-sync
import os
import json
# Get local storage and store as env variable
local_storage = page.evaluate("() => JSON.stringify(window.localStorage)")
os.environ["LOCAL_STORAGE"] = local_storage
# Save storage state and store as an env variable
storage = context.storage_state()
os.environ["STORAGE"] = json.dumps(storage)

# Set local storage in a new context
local_storage = os.environ["LOCAL_STORAGE"]
context.add_init_script("""storage => {
if (window.location.hostname == 'example.com') {
entries = JSON.parse(storage)
Object.keys(entries).forEach(key => {
window.localStorage.setItem(key, entries[key])
})
}
}""", local_storage)
# Create a new context with the saved storage state
storage_state = json.loads(os.environ["STORAGE"])
context = browser.new_context(storage_state=storage_state)
```

### Session storage

Session storage ([`window.sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage))
is specific to a particular domain.
is specific to a particular domain. Playwright does not provide API to persist session storage, but the following snippet can be used to save/load session storage.

```js
// Get session storage and store as env variable
Expand Down Expand Up @@ -247,12 +186,11 @@ on any external state.
### Example

[This example script](https://github.com/microsoft/playwright/blob/master/docs/examples/authentication.js) logs in
on GitHub.com with Chromium, and then reuses the logged in cookie state in WebKit.
on GitHub.com with Chromium, and then reuses the logged in storage state in WebKit.

### API reference
- [BrowserContext]
- [`method: BrowserContext.cookies`]
- [`method: BrowserContext.addCookies`]
- [`method: BrowserContext.storageState`]
- [`method: Browser.newContext`]
- [`method: Page.evaluate`]
- [`method: BrowserContext.addInitScript`]

Expand Down