12

当用户在 Django 中进行身份验证时,如何从美味派中检查?

用户登录后,视图会包含一些从 API 中提取数据的 JS,这些 JS 由美味派支持。

我在资源上设置了基本身份验证/djangoauthorisation,因此浏览器会弹出 http auth 窗口。有没有办法避免这种情况?

到目前为止,我的想法是扩展 BasicAuthentication 以便它首先检查会话数据,当它没有找到它时,它会退回到 http auth?AFAIK AJAX 调用包括会话 cookie,所以理论上这应该有效吗?有没有人做过类似的事情?

4

4 回答 4

10

到目前为止,我有这个解决方案:

class MyBasicAuthentication(BasicAuthentication):
    def __init__(self, *args, **kwargs):
        super(MyBasicAuthentication, self).__init__(*args, **kwargs)

    def is_authenticated(self, request, **kwargs):
        from django.contrib.sessions.models import Session
        if 'sessionid' in request.COOKIES:
            s = Session.objects.get(pk=request.COOKIES['sessionid'])
            if '_auth_user_id' in s.get_decoded():
                u = User.objects.get(id=s.get_decoded()['_auth_user_id'])
                request.user = u
                return True
        return super(MyBasicAuthentication, self).is_authenticated(request, **kwargs)

这似乎做了我想要的。如果用户已登录,则会话包含_auth_user_id,如果没有,则缺少密钥。

任何人都可以想到这种方法可能导致的任何问题?

于 2011-09-09T15:43:21.453 回答
9

你可能想在 sweetpie 的 GitHub 上查看这张票:

https://github.com/toastdriven/django-tastypie/issues/197

作者提出了一种非常简洁的方法来使用会话和 API 密钥方法对调用进行身份验证。

片段如下:

class ApiKeyPlusWebAuthentication(ApiKeyAuthentication):
def is_authenticated(self, request, **kwargs):
    if request.user.is_authenticated():
        return True

    return super(ApiKeyPlusWebAuthentication, self).is_authenticated(request, **kwargs)

def get_identifier(self, request):
    if request.user.is_authenticated():
        return request.user.username
    else:
        return super(ApiKeyPlusWebAuthentication, self).get_identifier(request)
于 2011-11-29T20:46:25.667 回答
1

一旦用户通过您的 API 登录,您就有了一个 Django 用户会话。如果您想检查用户是否仍然登录(例如在页面刷新时)。你可以做:

from tastypie.resources import Resource

class LoggedInResource(Resource):
    class Meta:
        pass

    def get_list(self, request, **kwargs):

        from django.http import HttpResponse

        if request.user.is_authenticated():
            return HttpResponse(status=200)
        else:
            return HttpResponse(status=401)

客户检查:

$.ajax({
    type: "GET",
    url: '/api/loggedin/',
    success: function(data) {
        // logged in
    },
    error: function() {
        // not logged in
    }
});
于 2013-03-11T20:03:39.870 回答
0

芹菜

为什么不简单如下:

class CommAuthentication(BasicAuthentication):
    def __init__(self, *args, **kwargs):
        super(CommAuthentication, self).__init__(*args, **kwargs)

    def is_authenticated(self, request, **kwargs):
        return request.user.is_authenticated()

我刚开始学习美味派。上面的代码似乎对我有用。您的解决方案有什么优势吗?

于 2011-12-17T15:13:29.490 回答