Django - 没有型号的登录用户

时间:2015-12-07 17:23:53

标签: python django django-authentication

我正在尝试实施SSO登录,从saml响应中获取所有授权权限:

class SAMLServiceProviderBackend(object):

    def authenticate(self, saml_authentication=None):
        if not saml_authentication:  # Using another authentication method
            return None

        if saml_authentication.is_authenticated():
            attributes = saml_authentication.get_attributes()
            user = User(username=saml_authentication.get_nameid())
            user.first_name = attributes['givenName']
            user.last_name = attributes['sn']

        return None

在视图中我得到了类似

的内容
...
user = authenticate(saml_authentication=auth)
login(self.request, user)
...
由于缺少login方法,

save()失败。唯一的方法是从User继承并覆盖save方法。试着这个,我得到了is_authenticatedget_and_delete_messages的下一个错误,依此类推

是否有一种简单的方法可以将用户对象插入到会话中,而无需将用户保存到数据库?

类似的东西:

request.session['user'] = authenticate(saml_authentication=auth)

2 个答案:

答案 0 :(得分:1)

我非常确定Django的会话对象是身份验证后端所必需的。即如果你登录,那么Django需要在某个地方存储对这个事实的引用。 Django通常使用它的数据库来执行此操作,但是,如果您没有在您的应用程序中使用数据库,那么您可以改为查看缓存会话:

https://docs.djangoproject.com/en/1.11/topics/http/sessions/#using-cached-sessions

(我假设您没有使用根据您的问题判断的数据库)

但更重要的是,根据您的需求,您可能需要查看创建/配置自定义用户模型以使后端工作:

https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#substituting-a-custom-user-model

答案 1 :(得分:0)

我想应该可以有一些限制,例如。用户为FK时无法保存数据。

我自己试过这个,我怀疑你可以在authenticate()方法中动态创建一个用户实例,只是不要调用user.save(),或者覆盖save()方法什么都不做

您可能还需要在请求之间连接用户记录,因此您可能需要为用户编写自己的序列化程序,并从会话中重新构造用户实例。