I wanted to know the best way to authenticate users in a chrome extension using a django website, like when the user is logged in in the website, he will be logged in in the extension as well, however I don't want to use Django rest framework, I have a classical Django website, I tried to read cookies form the extension, but I don't know if its a good solution, and I couldn't send the information from the service worker to the content script, I want to know the best way (and modern with manifest v3 and Django 4) to handle this, (I want to implement this to manage Stripe payments). Thank you for your answer.
I have solved the problem by getting the session id cookie from the chrome extension and each time I make a request to the server, it checks if the session key is valid or not using this code:
@csrf_exempt
def django_view(request):
data = json.loads(request.body)
session_key = data['sessionid'] // getting the session id from the request body
session = Session.objects.filter(session_key=session_key) // filter Session objects
if not session.exists(): // check if session id is valid (exists in DB)
return JsonResponse({
'error': 'Authentication required in www.mywebsite.com',
}, status=401)
return JsonResponse({
'error': 'You are logged in in www.mywebsite.com',
}, status=200)
contentScripts.js:
(async () => {
const response = await chrome.runtime.sendMessage({request: "sessionid"}); // sending a message to the service worker to get the cookie
if (response.sessionid !== null) {
// When making a request
event.stopPropagation();
fetch('http://mywebsite.com/api/something', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ video_url: window.location.href, sessionid: response.sessionid })
});
} else {
// if the session id is null, open the django login page in a new tab
window.open('http://mywebsite.com/login', '_blank');
}
})();
service_worker.js:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.request === "sessionid") {
var myPromise = chrome.cookies.get({"url": 'http://mywebsite.com', "name": 'sessionid'});
myPromise.then((result) => {
if (result !== null) {
sendResponse({sessionid: result.value});
} else {
sendResponse({sessionid: null});
}
}).catch((error) => {
console.error(error);
});
}
return true;
}
);
And finally for accessing cookies of a website in a chrome extension, you should give the permission in your manifest.json
:
"host_permissions": [
"http://mywebsite.com"
]