使用ldap3验证django应用程序

时间:2017-03-13 13:31:20

标签: python django ldap ldap3

我的django应用中的身份验证用户有问题。我使用的是Python 3.5和Django 1.10。

我编写了简单的绑定配置来检查用户是否真的是来自数据库的用户:

    username = request.POST['username']
    password = request.POST['password']

    server = Server(LDAP_AUTH_URL)
    c = Connection(server, user=LDAP_AUTH_CONNECTION_USERNAME, password=LDAP_AUTH_CONNECTION_PASSWORD)

    c.open()
    c.bind()

    if c.bind():
        user_search_filter = '(uid={})'.format(username)
        c.search(search_base=LDAP_AUTH_SEARCH_BASE,
                 search_filter=user_search_filter,
                 search_scope=SUBTREE)

    username = c.response[0]['dn']
    if c.rebind(user=username, password=password):
        return HttpResponseRedirect(next)

但现在我不知道该怎么做,在django我们当然有这样的事情:

    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            auth.login(request, user)
            return HttpResponseRedirect(next)
        else:
            return render(request, 'login.html', {'error_message': 'Your account has been disabled'})
    else:
        return render(request, 'login.html', {'error_message': 'Invalid login'})

但在这种情况下,我们必须在我们的基地拥有用户帐户,而不是来自ldap授权。

因此,当我通过ldap登录时,我希望获得django的授权,以便使用“@ login_required”访问任何其他视图

我对ldap和ldap3 for Python> 3的想法可能有问题。

有人可以帮我或给我有用的链接吗?

2 个答案:

答案 0 :(得分:0)

拆分用户授权管理。

添加功能以检查ldap auth。假设它将通过提供的凭据返回True/False

def ldap_auth(login, password):
    ...
    return c.bind()

因此,在身份验证视图中,您现在需要为ldap和非ldap用户提供两种不同的条件:

# if it is ldap user check ldap_auth
# if user doesn't exist locally you could create it manually in case of successful auth
else:
    user = authenticate(username=username, password=password)

在前端你需要以某种方式指定它是否是ldap用户。或者你可以进一步根据几个检查添加一些逻辑:尝试在普通用户中找到用户,如果没有结果 - 尝试通过ldap登录。

答案 1 :(得分:0)

为LDAP身份验证添加django身份验证后端,例如: /users/auth/backend.py并在您的settings.py中为django配置此后端,以便将其用于所有登录呼叫。

添加实现LDAP身份验证的authenticate()方法。您还需要实现get_user()方法。

建议您在首次登录时或在应用程序中首次在活动目录中搜索用户时同步LDAP中的用户帐户,并维护应用程序的用户模型。

有关设置身份验证后端和同步用户的更多信息,请访问:

Customizing Django Authentication Bakcend