django-auth-ldap failed authentication - django

I'm trying to use Django-Auth-Ldap in my project (Django 1.6, Python 2.7) but it is not working.
My active Directory shema is:
I've tested the connection on the cmd line by installing the ldap-utils package
sudo apt-get install ldap-utils
ldapsearch -H ldap://domain.com -D "ou=Resources,ou=Company, dc=domain,dc=com" -U "user_name" -w "user_password" -v -d 1
The connection test works fine.
I am using below code to test python-ldap connection from the shell:
import ldap
con = ldap.initialize('ldap://domain.com')
con.simple_bind_s('User_mail', 'User_password')
results = con.search_s('ou=Users,ou=Resources,ou=Company,dc=domain,dc=com', ldap.SCOPE_SUBTREE, "(cn=User_name)")
python-ldap connection works fine.
My problem is how to authenticate AD users from my django login interface?
settings.py:
import ldap
from django_auth_ldap.config import LDAPSearch
# The URL of the LDAP server.
AUTH_LDAP_SERVER_URI = "ldap://domain.com"
AUTH_LDAP_BIND_DN = "cn='User_name',ou=Resources,ou=Company,dc=domain,dc=com"
AUTH_LDAP_BIND_PASSWORD = "User_password"
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=Users,ou=Resources,ou=Company,dc=domain,dc=com",ldap.SCOPE_SUBTREE, "(cn=%(user)s)")
AUTH_LDAP_GLOBAL_OPTIONS = { ldap.OPT_REFERRALS : False }
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
views.py:
from django_auth_ldap.backend import LDAPBackend
auth = LDAPBackend()
user = auth.authenticate(username="User_name", password="User_password")
In the file django-ldap-debug.log I have this error:
Caught LDAPError while authenticating User_name: INVALID_CREDENTIALS({'info': '80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1', 'desc': 'Invalid credentials'},)

I found the answer.
I changed the AUTH_LDAP_BIND_DN by adding (OU=Users)
I must use samAccountName instead of CN in AUTH_LDAP_USER_SEARCH
My new settings.py :
import ldap, logging
from django_auth_ldap.config import LDAPSearch
logger = logging.getLogger('django_auth_ldap')
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)
AUTH_LDAP_SERVER_URI = "ldap://domain.com"
AUTH_LDAP_BIND_DN = "CN=User_name,OU=Users,OU=Resources,OU=Company,DC=domain,DC=com"
AUTH_LDAP_BIND_PASSWORD = "User_password"
AUTH_LDAP_USER_SEARCH = LDAPSearch("OU=Users,OU=Resources,OU=Company,DC=domain,DC=com",ldap.SCOPE_SUBTREE, "(samAccountName=%(user)s)")
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
My views.py
from django_auth_ldap.backend import LDAPBackend
def login(request):
if request.method == 'POST':
form = MyLoginForm(data=request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
auth = LDAPBackend()
user = auth.authenticate(username=username, password=password)
if user is not None:
....
else:
form = MyLoginForm()
....
Hope this help all :)

I had similar problem but I have solved it other way around. Under AUTH_LDAP_BIND_DN have just put the user and domain and password. After that this was working like charm...
While I was investigating my ldaps issues I found above solution somehow useful, maybe also someone will benefit with my solution
LDAP_IGNORE_CERT_ERRORS = True
AUTH_LDAP_START_TLS = False
AUTH_LDAP_SERVER_URI = "ldaps://domain.com:636"
AUTH_LDAP_BIND_DN = "serviceaccount#domain.com"
AUTH_LDAP_BIND_PASSWORD = "superPass"
AUTH_LDAP_USER_SEARCH = LDAPSearch(
"OU=Company,DC=domain,DC=com",ldap.SCOPE_SUBTREE,"(sAMAccountName=%(user)s)"
)
AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenName",
"last_name": "sn",
"email": "mail"
}

Related

How can I send a reset password email on Django?

During the process of creating my first website using Django framework, I encountered a little problem that I couldn't found a solution yet. So, when an user wants to reset his or her password, i'd like to send to him/her a reset mail. So far, I have this:
urls.py
from django.contrib.auth import views as auth_views
......
path('password-reset/', auth_views.PasswordResetView.as_view(template_name='registration/password_reset_form.html'),
name='password_reset'),
path('password-reset-confirm/<uidb64>/<token>/',
auth_views.PasswordResetConfirmView.as_view(template_name='registration/password_reset_confirm.html'),
name='password_reset_confirm'),
path('password-reset/done/',
auth_views.PasswordResetDoneView.as_view(template_name='registration/password_reset_done.html'),
name='password_reset_done'),
path('password-reset-complete/',
auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html')),
....
settings.py
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_POST = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ.get('traces_email')
EMAIL_HOST_PASSWORD = os.environ.get('traces_email_password')
I created a token generator for my link:
token_generator.py
from django.contrib.auth.tokens import PasswordResetTokenGenerator
import six
class TokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return (
six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active)
)
account_activation_token = TokenGenerator()
When I go through the reset flow, it does not send any email. It is still sent to my terminal.
Can somebody help me with this issue? Thank you so much for your time!
This setting
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
tells django to send the message to your terminal. To actually send an email, you need to use
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
This is described in the Django Docs.

Django: Unable to get user's groups from LDAP user

My Django ( Django 1.11) project is using django-auth-ldap 1.2 as authentication backed.
I have no problem to authenticate any user agents LDAP database using:
#login_required(login_url='/accounts/login/')
and in this case, any user from any group can login to the site.
I want to allow only user from 'group1' to be able to access the website.
I used the code listed below
from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import views as auth_views
#user_passes_test(
lambda u: hasattr(u, 'ldap_user') and 'group1' in u.ldap_user.group_names,
login_url='/accounts/login/')
def index(request):
template = loader.get_template('main/index.html')
return HttpResponse(template.render())
This is code is not working and user will never pass the test.
According to the model documents django-auth-ldap Document I can use ldap_user.group_names to get group names of a user.
Here is my ldap settings from settings.py:
import os
import django
AUTHENTICATION_BACKENDS = ('django_auth_ldap.backend.LDAPBackend',)
import ldap
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType
AUTH_LDAP_SERVER_URI = "ldap://mydomain.com"
AUTH_LDAP_BIND_DN = "cn=admin,dc=mydomain,dc=com"
AUTH_LDAP_BIND_PASSWORD = "mypass"
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=ou_org_unit,dc=mydomain,dc=com",
ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=ou_org_unit,cn=group1,cn=group2,dc=mydomain,dc=com",
ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)"
)
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType()
AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenName",
"last_name": "sn",
"email": "mail"
}
AUTH_LDAP_FIND_GROUP_PERMS = True
AUTH_LDAP_CACHE_GROUPS = True
AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600
My question is:
Why I am not able to authenticate any user with this code?
You should be using the AUTH_LDAP_REQUIRE_GROUP setting if you want to restrict logins to a single group.
You will also likely want to use AUTH_LDAP_MIRROR_GROUPS in order to have all of your LDAP groups automatically loaded into your Django database.
As a bonus, you can include multiple groups in the AUTH_LDAP_REQUIRE_GROUP setting, by using the LDAPGroupQuery class. For example (taken from the documentation):
from django_auth_ldap.config import LDAPGroupQuery
AUTH_LDAP_REQUIRE_GROUP = (
(
LDAPGroupQuery("cn=enabled,ou=groups,dc=example,dc=com") |
LDAPGroupQuery("cn=also_enabled,ou=groups,dc=example,dc=com")
) &
~LDAPGroupQuery("cn=disabled,ou=groups,dc=example,dc=com")
)

How to authenticate in django using custom backend

I am using django-mongoengine to use mongodb with django. I manually created a document containing user_data in user collection manually like this:
The user and django_session were created automatically when I integrated the module and ran the project
Now I tried to authenticate user like this:
def loginAction(request):
if request.is_ajax():
email = request.POST.get('email')
password = request.POST.get('password')
user = authenticate(email=email, password=password)
print user
if user:
if user.is_authenticated():
login(request, user)
return HttpResponse(json.dumps({'RESULT':'SUCCESS'}),content_type="application/json")
else:
return HttpResponse(json.dumps({'RESULT':'FAILURE'}),content_type="application/json")
However It is returning None when I am trying to print user.
I tried several codes but i am still not able to authenticate.
My settings.py :
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_mongoengine',
'django_mongoengine.mongo_auth',
'login_app',
]
MONGODB_DATABASES = {
'default': {'name': 'picknbox'}
}
DATABASES = {
'default': {'ENGINE': 'django.db.backends.dummy'}
}
AUTH_USER_MODEL = 'mongo_auth.MongoUser'
AUTHENTICATION_BACKENDS = (
'django_mongoengine.mongo_auth.backends.MongoEngineBackend',
)
SESSION_ENGINE = 'django_mongoengine.sessions'
My question is how to authenticate using the django-mongoengine backend?
Note: I tried the same approach with sqlite database using custom backend and it worked. I was able to authenticate as well as login and logout was working fine.
EDIT: I checked the MongoEngineBackend class in AUTHENTICATION_BACKENDS and it is defined as:
from django.contrib import auth
class MongoEngineBackend(object):
"""Authenticate using MongoEngine and mongoengine.django.auth.User.
"""
supports_object_permissions = False
supports_anonymous_user = False
supports_inactive_user = False
authenticate = auth.backends.ModelBackend.__dict__["authenticate"]
get_user = auth.backends.ModelBackend.__dict__["get_user"]
so it uses the django's auth.

Cannot pass APP ID while using Django Social Auth

I am trying to enable logging in via facebook,twitter and Google Open Auth 2. I am using the main documentation https://django-social-auth.readthedocs.org/en/latest/index.html. I have also used http://c2journal.com/2013/01/24/social-logins-with-django/
I have put all the necessary configurations in place. Here is my settings.py
....
AUTHENTICATION_BACKENDS = (
'social_auth.backends.twitter.TwitterBackend',
'social_auth.backends.facebook.FacebookBackend',
'social_auth.backends.google.GoogleOAuthBackend',
'social_auth.backends.google.GoogleOAuth2Backend',
'social_auth.backends.google.GoogleBackend',
'django.contrib.auth.backends.ModelBackend',
)
.....
TEMPLATE_CONTEXT_PROCESSORS = (
"social_auth.context_processors.social_auth_by_type_backends",
"django.contrib.auth.context_processors.auth",
)
......
SOCIAL_AUTH_ENABLED_BACKENDS = ('google','facebook','twitter')
.....
FACEBOOK_APP_ID='**********'
FACEBOOK_API_SECRET='**********************'
FACEBOOK_APP_NAMESPACE = '********_app'
FACEBOOK_EXTENDED_PERMISSIONS = ['email']
GOOGLE_OAUTH2_CLIENT_ID = '***************'
GOOGLE_OAUTH2_CLIENT_SECRET = '**************************'
TWITTER_CONSUMER_KEY = '***************'
TWITTER_CONSUMER_SECRET = '**********************'
........
INSTALLED_APPS = (
............
'social_auth',
)
I have added social-auth to my urls.py too
(r'^accounts/login/$', 'django.contrib.auth.views.login',
{'template_name': 'login.html'}),
(r'^accounts/logout/$', 'django.contrib.auth.views.logout_then_login'),
.....
urlpatterns = patterns('',
...
url(r'', include('social_auth.urls')),
...
)
On my login.html page, here is how I have called the links
<div>Login with Facebook</div>
</div>Login with Twitter</div>
</div>Login with Google</div>
The problem however, everytime I try logging in via any of these services, It seems the APP Id is missing.
I get this error on Facebook Invalid App ID: None and this one on twitter Only unicode objects are escapable. Got None of type .. Google doesn't work too but It tells me I cannot use raw IP addresses. I am using the server IP address. Please help.
I figured out what was the problem. I had installed python social auth then installed django-social auth. My application was still using the python-social-auth package.
Using the python-social-Auth syntax of naming configuration variables, I added the prefix
SOCIAL_AUTH_
to my config variables so that they now looked like this
SOCIAL_AUTH_FACEBOOK_SECRET='*******************'
SOCIAL_AUTH_FACEBOOK_APP_NAMESPACE = '*******'
SOCIAL_AUTH_FACEBOOK_EXTENDED_PERMISSIONS = ['email']
SOCIAL_AUTH_TWITTER_KEY = '********'
SOCIAL_AUTH_TWITTER_SECRET = '************'
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '*************************************'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '****************'
I can now log in. Thanks

how to use ldap for authentication for app in django?

I want to use LDAP authentication for my application. My application is taking the input from user and storing details such as firstname,lastname in database. When I write following code in my settings.py file but I didn't get any error for that and application is running normally. So how can I know that LDAP is using in app or need some modifications in app. Please help me. I used basic settings from Django documentation.
import ldap
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType
# Baseline configuration.
AUTH_LDAP_SERVER_URI = "ldap://ldap.example.com"
AUTH_LDAP_BIND_DN = "cn=django-agent,dc=example,dc=com"
AUTH_LDAP_BIND_PASSWORD = "marksheet"
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=example,dc=com",
ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=django,ou=groups,dc=example,dc=com",
ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)"
)
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn")
AUTH_LDAP_REQUIRE_GROUP = "cn=enabled,ou=django,ou=groups,dc=example,dc=com"
AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "firstname",
"last_name": "lastname",
}
Thanks...
It seems you are trying to do this using the django-auth-ldap package. For this setup, your settings are missing the most important part, namely adding django_auth_ldap.backend.LDAPBackend to your AUTHENTICATION_BACKENDS.
Refer to the django-auth-ldap documentation for more detailed setup instructions.