I have a website that I built in Flask which can only be accessed if you are in Active Directory. I want to limit that scope to group membership but I cant figure out how to do it.
Here is my code so far:
@app.route('/login', methods=["GET", "POST"])
def login():
session.permanent = True
if g.user is not None and g.user.is_authenticated():
return redirect(url_for('main'))
if request.method == 'POST':
login = LoginValidator(username=request.form.get('username'),
password=request.form.get('password'))
if login.is_valid:
login_user(login.lookup_user, remember=False)
string = 'You have logged in as '+ g.user.username
flash(string, 'success')
return redirect(url_for('main'))
else:
username=request.form.get('username')
password=request.form.get('password')
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
sess = ldap.initialize('LDAP_SERVER')
sess.set_option(ldap.OPT_REFERRALS, 0) # referrals = 0
sess.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
try:
sess.bind_s("%s@example.net" % username, password)
numuser = len(User.query.all())
hash = sha256_crypt.encrypt(password)
u = User(id=numuser+1,
username=username,
password=hash,
role="ROLE_USER")
db.session.add(u)
db.session.commit()
flash('User added to the database, please login again', 'info')
except:
flash('Incorrect Login/Password', 'danger')
return render_template('login.html')
What this is doing is checking to see if the username and password is in the database and, if it is not, attempts to bind to the LDAP server with the username and password specified. If the bind is successful, then it hashes the password and adds the username and hashed password to the database.
The problem with this solution is that anyone in Active Directory has access to the website. How is it possible to allow only members of a certain group access?
If you would be using Flask-ldap, there's a config option to be set up:
http://flask-ldap.readthedocs.org/en/latest/setting%20it%20up.html
LDAP_REQUIRED_GROUP - If specified, the authentication must succeed AND the user must be part of this security group. (Ex: “CN=security_group_name,OU=Groups,DC=example,DC=com” )