簡體   English   中英

ldap3認證django應用

[英]authentication django app with 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”訪問任何其他視圖

對於python> 3的ldap和ldap3,我的想法也許有問題。

有人可以幫助我或給我有用的鏈接嗎?

分開管理用戶授權。

添加功能以檢查ldap身份驗證。 說它將通過提供的憑據返回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登錄。

為LDAP身份驗證添加django身份驗證后端,例如: /users/auth/backend.py並在您的settings.py中配置/users/auth/backend.py ,以使django將其用於所有登錄調用。

並添加實現LDAP身份authenticate()方法。 您還需要實現get_user()方法。

建議您在首次登錄時或從應用程序內部首次在活動目錄中搜索用戶時從LDAP同步用戶帳戶,並維護應用程序的用戶模型。

可在此處找到有關設置身份驗證后端和同步用戶的更多信息:

自定義Django身份驗證Bakcend

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM