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

This commit is contained in:
Dmitry Gozman 2021-01-08 12:24:10 -08:00 committed by GitHub
parent d08cbc33a7
commit 498f9a52c6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 96 deletions

View file

@ -3,13 +3,13 @@ const assert = require('assert');
/** /**
* In this script, we will login on GitHub.com through Chromium, * 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. * used to speed up tests by logging in once and reusing login state.
* *
* Steps summary * Steps summary
* 1. Login on GitHub.com in Chromium * 1. Login on GitHub.com in Chromium
* 2. Export cookies from Chromium browser context * 2. Export storage state from Chromium browser context
* 3. Set cookies in WebKit browser context and verify login * 3. Set storage state in WebKit browser context and verify login
*/ */
const account = { login: '', password: '' }; const account = { login: '', password: '' };
@ -31,14 +31,13 @@ const account = { login: '', password: '' };
await crPage.click('input[type="submit"]'); await crPage.click('input[type="submit"]');
await verifyIsLoggedIn(crPage); await verifyIsLoggedIn(crPage);
// Get cookies from Chromium browser context // Get storage state from Chromium browser context
const cookies = await crContext.cookies(); const storageState = await crContext.storageState();
await crBrowser.close(); await crBrowser.close();
// Create WebKit browser context and load cookies // Create WebKit browser context with saved storage state
const wkBrowser = await webkit.launch(); const wkBrowser = await webkit.launch();
const wkContext = await wkBrowser.newContext(); const wkContext = await wkBrowser.newContext({ storageState });
await wkContext.addCookies(cookies)
// Navigate to GitHub.com and verify that we are logged in // Navigate to GitHub.com and verify that we are logged in
const wkPage = await wkContext.newPage(); const wkPage = await wkContext.newPage();

View file

@ -69,114 +69,53 @@ existing authentication state in new browser contexts.
Web apps use cookie-based or token-based authentication, where authenticated 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) 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). 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 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.
and then load it into new contexts.
Cookies and local storage state can be used across different browsers. They depend 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 on your application's authentication model: some apps might require both cookies
and local storage. and local storage.
The following code snippets retrieve state from an authenticated page/context and The following code snippet retrieves state from an authenticated context and
load them into a new context. creates a new context with that state.
### Cookies
```js ```js
// Get cookies and store as an env variable // Save storage state and store as an env variable
const cookies = await context.cookies(); const storage = await context.storageState();
process.env.COOKIES = JSON.stringify(cookies); process.env.STORAGE = JSON.stringify(storage);
// Set cookies in a new context // Create a new context with the saved storage state
const deserializedCookies = JSON.parse(process.env.COOKIES) const storageState = JSON.parse(process.env.STORAGE);
await context.addCookies(deserializedCookies); const context = await browser.newContext({ storageState });
``` ```
```python-async ```python-async
import json import json
import os import os
# Get cookies and store as an env variable # Save storage state and store as an env variable
cookies = await context.cookies() storage = await context.storage_state()
os.environ["COOKIES"] = json.dumps(cookies) os.environ["STORAGE"] = json.dumps(storage)
# Set cookies in a new context # Create a new context with the saved storage state
deserialized_cookies = json.loads(os.environ["COOKIES"]) storage_state = json.loads(os.environ["STORAGE"])
await context.add_cookies(deserialized_cookies) context = await browser.new_context(storage_state=storage_state)
``` ```
```python-sync ```python-sync
import json import json
import os import os
# Get cookies and store as an env variable # Save storage state and store as an env variable
cookies = context.cookies() storage = context.storage_state()
os.environ["COOKIES"] = json.dumps(cookies) os.environ["STORAGE"] = json.dumps(storage)
# Set cookies in a new context # Create a new context with the saved storage state
deserialized_cookies = json.loads(os.environ["COOKIES"]) storage_state = json.loads(os.environ["STORAGE"])
context.add_cookies(deserialized_cookies) context = browser.new_context(storage_state=storage_state)
```
### 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
# 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)
``` ```
### Session storage ### Session storage
Session storage ([`window.sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage)) 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 ```js
// Get session storage and store as env variable // Get session storage and store as env variable
@ -247,12 +186,11 @@ on any external state.
### Example ### Example
[This example script](https://github.com/microsoft/playwright/blob/master/docs/examples/authentication.js) logs in [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 ### API reference
- [BrowserContext] - [`method: BrowserContext.storageState`]
- [`method: BrowserContext.cookies`] - [`method: Browser.newContext`]
- [`method: BrowserContext.addCookies`]
- [`method: Page.evaluate`] - [`method: Page.evaluate`]
- [`method: BrowserContext.addInitScript`] - [`method: BrowserContext.addInitScript`]