在Chrome扩展中处理与Django网站的身份验证

huangapple go评论65阅读模式
英文:

Handle authentication in chrome extension with a Django website

问题

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 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.

答案1

得分: 0

I have translated the code as requested:

@csrf_exempt
def django_view(request):
    data = json.loads(request.body)
    session_key = data['sessionid']  # 从请求体中获取会话ID
    session = Session.objects.filter(session_key=session_key)  # 过滤会话对象
    if not session.exists():  # 检查会话ID是否有效(存在于数据库中)
        return JsonResponse({
            'error': '需要在 www.mywebsite.com 中进行身份验证',
        }, status=401)

    return JsonResponse({
        'error': '您已登录 www.mywebsite.com',
    }, status=200)
(async () => {
    const response = await chrome.runtime.sendMessage({ request: "sessionid" });  // 发送消息给服务工作器以获取Cookie
    if (response.sessionid !== null) {
        // 在发出请求时
        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 {
        // 如果会话ID为null,则在新标签页中打开Django登录页面
        window.open('http://mywebsite.com/login', '_blank');
    }
})();
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;
    }
);

最后,在Chrome扩展中访问网站的Cookie,您需要在您的manifest.json中授予权限:

"host_permissions": [
    "http://mywebsite.com"
]
英文:

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"
]

huangapple
  • 本文由 发表于 2023年5月7日 19:42:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76193711.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定