Flask-login和LDAP

9

我正在使用 Flask 框架作为后端开发 Web 应用程序,并且需要提供身份验证。

由于这是一个内部应用程序,将在我们的本地域上使用,因此我选择使用已有的域凭据对用户进行身份验证。

我使用的方法是从 pywin32 中调用 win32security.LogonUser,成功登录后返回一个句柄。

我尝试理解 Flask-Login 的工作原理,但是 @login_manager.user_loader 回调让我感到困惑。

它说我应该提供一个 ID,可以用来重新加载用户,但是我没有数据库或持久存储来提供此映射,因为我只关心检查用户是否通过身份验证。

我的 User 类看起来像这样:

class User(flask_login.UserMixin):
    def __init__(self,username):
        self.username = username
        self.id = ??? 

如何使用id,并且这个id如何映射回该实例?


如果您正在使用LDAP后端,则应该将用户的DN用作ID。 - Mark E. Haase
4个回答

11
您可以使用Python的LDAP模块来完成此操作:
LDAP_SERVER = "yourldapserver"
LDAP_PORT = 390033 # your port
import ldap
def login(email, password):
    ld = ldap.open(LDAP_SERVER, port=LDAP_PORT)
    try:
        ld.simple_bind_s(email, password)
    except ldap.INVALID_CREDENTIALS:
        return False
    return True

6

4

使用ldap3实现flask-login的简单示例。

from flask_ldap3_login.forms import LDAPLoginForm
from flask_ldap3_login import LDAP3LoginManager, AuthenticationResponse
from flask_login import LoginManager, login_user, UserMixin, current_user
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['DEBUG'] = 'True'
# Setup LDAP Configuration Variables. Change these to your own settings.


# Hostname of your LDAP Server
app.config['LDAP_PORT'] = 636
# Hostname of your LDAP Server
app.config['LDAP_HOST'] = 'ldap-name.com'
app.config['LDAP_USE_SSL'] = True
# Base DN of your directory
app.config['LDAP_BASE_DN'] = 'dc=Hostname,dc=com'

# Users DN to be prepended to the Base DN
app.config['LDAP_USER_DN'] = 'ou=people'

# Groups DN to be prepended to the Base DN
app.config['LDAP_GROUP_DN'] = 'cn=ldap-groupname,ou=groups'

# The RDN attribute for your user schema on LDAP
app.config['LDAP_USER_RDN_ATTR'] = 'uid'

# The Attribute you want users to authenticate to LDAP with.
app.config['LDAP_USER_LOGIN_ATTR'] = 'uid'
# The Username to bind to LDAP with
app.config['LDAP_BIND_USER_DN'] = 'uid'
# The Password to bind to LDAP with
app.config['LDAP_BIND_USER_PASSWORD'] = 'pwd'
login_manager = LoginManager(app)  # Setup a Flask-Login Manager
ldap_manager = LDAP3LoginManager(app)  # Setup a LDAP3 Login Manager.
# Create a dictionary to store the users in when they authenticate
# This example stores users in memory.
users = {}
# Declare an Object Model for the user, and make it comply with the
# flask-login UserMixin mixin.
class User(UserMixin):
 def __init__(self, dn, username, data):
    self.dn = dn
    self.username = username
    self.data = data

def __repr__(self):
    return self.dn

def get_id(self):
    return self.dn

# Declare a User Loader for Flask-Login.
# Simply returns the User if it exists in our 'database', otherwise
# returns None.
@login_manager.user_loader
def load_user(id):
    if id in users:
       return users[id]
    return None
# Declare The User Saver for Flask-Ldap3-Login
# This method is called whenever a LDAPLoginForm() successfully validates.
# Here you have to save the user, and return it so it can be used in the
# login controller.

@ldap_manager.save_user
def save_user(dn, username, data, memberships):
  user = User(dn, username, data)
  users[dn] = user
  return user,username
@app.route('/', methods=['GET', 'POST'])
def login():
 # exists in LDAP.
 form = LDAPLoginForm()
 if form.validate_on_submit():
        # Successfully logged in, We can now access the saved user object
        # via form.user.
        a = login
        return redirect(url_for('mainpage'))
    return render_template('login.html',form=form)
else:
    return render_template('error.html')

我仍然困惑于如何将id传递给login_manager?我们何时调用load_user或save_user来将ldap的信息传递给它? - frlzjosh

1

self.id应该是一个唯一的字符串。它可以是以下之一:

  • cn(在LDAP中唯一)
  • sAMAccountName(在域中唯一,类似于Unix登录名)
  • mail(多值,其中一个应该/可以是唯一的)
  • ...

只需选择一个,并明智地选择。我更喜欢sAMAcountName用于我的工作。这需要您在ldap_bind后进行LDAPSearch。

第一次无需身份验证的绑定(以查找DN)应使用应用程序用户进行,以避免信息泄漏(如果您被黑客攻击)。

Ldap连接是资源=>使用上下文管理器

with ldap.open(LDAP_SERVER, port=LDAP_PORT) as ld:
    # do the search/bind/search here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接