I'm creating a Google Chrome extension which adds upload buttons to images on Instagram profile pages. The service the extension will be uploading to is Imgur.
Since I'll eventually want users to be able to upload to specific Imgur albums on their accounts, I need to obtain OAuth access tokens from the Imgur API.
To do this, I've done the following. When the extension icon in the browser is clicked, it opens up a new tab (not a pop-up). This tab opens index.html. Clicking the login button on that page calls the authorization URL.
But where do I safely store the access/refresh tokens once I've received them? I don't think I can put them in localStorage, because as far as I know, each origin has its own localStorage.
What's the best practice when it comes to storing OAuth 2.0 access tokens and refresh tokens when it comes to Chrome Extensions like mine?
// oauth.js
let loginStatus = false;
if (!loginStatus) {
createElement("p", "You are not logged in to Imgur.", "login-status");
createElement("button", "Login to Imgur", "login-status", loginToImgur);
} else {
createElement("p", "You are successfully logged in to Imgur.", "login-status");
createElement("button", "Signout of Imgur", "login-status", function() {
alert("this is a placeholder");
});
}
function createElement(type, text, parentId, onclick) {
const element = document.createElement(type);
const textNode = document.createTextNode(text);
element.appendChild(textNode);
if (onclick) {
element.onclick = onclick;
}
document.getElementById(parentId)
.appendChild(element);
return element;
}
function loginToImgur() {
const AUTH_URL = "https://api.imgur.com/oauth2/authorize?response_type=token&client_id=<INDIVIDUAL_CLIENT_ID>";
chrome.identity.launchWebAuthFlow({
url: AUTH_URL, // Opens a window to initiate Imgur OAuth authorization and obtain access token
interactive: true
}, function(responseUrl) {
console.log(responseUrl);
// The access token we want will be found in the response URL, somewhere after the # symbol.
extractToken(responseUrl);
});
}
function extractToken(responseURL) {
const accessToken = responseURL.split("#")[1]
.split("access_token=")[1]
.split("&")[0];
console.log(accessToken);
return accessToken;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Instagram to Imgur</title>
<link rel="stylesheet" href="styles/index.css">
</head>
<body>
<h1>Login page</h1>
<div id="login-status"></div>
</body>
<script src="scripts/content/oauth.js"></script>
</html>