Skip to content

Instantly share code, notes, and snippets.

@spkprav
Last active May 8, 2024 04:13
Show Gist options
  • Save spkprav/25c63e5797cdacc564da4c18f509eaea to your computer and use it in GitHub Desktop.
Save spkprav/25c63e5797cdacc564da4c18f509eaea to your computer and use it in GitHub Desktop.
Cookie Login in Chrome Extension
// This goes into background/index.js
function parseJwt(token) {
// Decode base64url encoded string
function base64UrlDecode(str) {
return decodeURIComponent(
atob(str.replace(/_/g, "/").replace(/-/g, "+"))
.split("")
.map(c => '%' + c.charCodeAt(0).toString(16).padStart(2, '0'))
.join("")
);
}
try {
// Split the JWT token into its three parts
const parts = token.split(".");
if (parts.length !== 3) {
throw new Error("Invalid JWT token");
}
// Decode the payload
const payload = JSON.parse(base64UrlDecode(parts[1]));
// Check the expiration time
const currentTime = Math.floor(Date.now() / 1000); // Current time in seconds since epoch
const isExpired = payload.exp && payload.exp < currentTime;
return {
payload,
isExpired,
};
} catch (error) {
console.error("Error decoding JWT token:", error);
return null;
}
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'validLogin') {
try {
chrome.cookies.get({ url: 'https://yourdomain', name: 'yourcookiename' }, (cookie) => {
const result = cookie ? parseJwt(cookie.value) : null;
if (result && !result.isExpired) {
console.log("Token Payload:", result.payload);
console.log("Is Token Expired?", result.isExpired);
sendResponse({ isValid: true });
} else {
console.log("Failed to decode the token");
sendResponse({ isValid: false });
}
});
} catch (error) {
sendResponse({ isValid: false });
}
return true; // keep the message channel open until sendResponse is called
}
});
// This goes into your content script
let isLoggedIn = false;
chrome.runtime.sendMessage({ action: 'validLogin' }, (response) => {
isLoggedIn = response.isValid;
});
// This goes into manifest
{
permissions: ['cookies'],
host_permissions: [
"https://yourdomain/*"
],
externally_connectable: {
matches: [
'https://yourdomain/*',
],
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment