问题
I know only two ways to get google OAuth token :
1. chrome.identity.getAuthToken() : Fetches token associated with chrome account. After restarting chrome, I can call getAuthToken()
method without logging. Works great. But doesn't work for non - google account.
2. chrome.identity.launchWebAuthFlow() : Works both for google and non- google account. But after restarting chrome, if call launchWebAuthFlow()
, it asks for login again. It is annoying.
What I want to achieve is to combine the functionalities of both :
Fetch OAuth token from both google and non-google account. And after restarting chrome, I can fetch token again without signing in.
If anyone knows how to use chrome.identity.launchWebAuthFlow()
to achieve the same or any other method??
回答1:
OAuth providers will return some sort of reusable access token, which can be re-used on subsequent logins. Usually these are very long-lived. For example, dropbox returns an access token in the responseUrl (in the callback from the web flow), matching a regex pattern /access_token=([^&]+)/
.
You can store this token in local storage and access it on subsequent attempts without going through the auth flow again.
The auth tokens don't always live forever (or they could be manually deauthorized), so you have to watch out for 401 response code, and do the web auth flow again if that occurs.
Logic ends up quite complex, something like:
- Get stored token
- If no stored token, then launch web flow and save auth token in local storage
- Try some operation using the stored token
- if 401, then redo auth flow and retry operation
来源:https://stackoverflow.com/questions/33954876/different-ways-to-fetch-oauth-token-from-an-extension