how to use ldap for authentication for app in django? - 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.

Related

How to troubleshoot a failing Django LDAP connection

I am using Django Rest with active directory authentication.
I have built a simple app with the following settings:
import ldap
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType
# Baseline configuration.
AUTH_LDAP_SERVER_URI = 'ldap://ad_server.com'
AUTH_LDAP_BIND_DN = "CN=binduser,OU=Users,OU=ad_server,DC=ad_server,DC=com"
AUTH_LDAP_BIND_PASSWORD = "somepassword"
# Set up the basic group parameters.
AUTH_LDAP_GROUP_SEARCH = LDAPSearch(
"OU=Groups,OU=ad_server,DC=ad_server,DC=com",
ldap.SCOPE_SUBTREE,
"(objectClass=groupOfNames)",
)
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn")
# Simple group restrictions
AUTH_LDAP_REQUIRE_GROUP = "CN=prod,OU=Groups,OU=ad_server,DC=ad_server,DC=com"
AUTH_LDAP_DENY_GROUP = "cn=disabled,ou=django,ou=groups,dc=example,dc=com"
# Populate the Django user from the LDAP directory.
AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenName",
"last_name": "sn",
'username': 'cn',
"email": "mail",
}
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
"is_active": "CN=prod,OU=Groups,OU=ad_server,DC=ad_server,DC=com",
"is_staff": "CN=prod,OU=Groups,OU=ad_server,DC=ad_server,DC=com",
"is_superuser": "CN=prod,OU=Groups,OU=ad_server,DC=ad_server,DC=com",
}
# This is the default, but I like to be explicit.
AUTH_LDAP_ALWAYS_UPDATE_USER = True
# Use LDAP group membership to calculate group permissions.
AUTH_LDAP_FIND_GROUP_PERMS = True
# Cache distinguished names and group memberships for an hour to minimize
# LDAP traffic.
AUTH_LDAP_CACHE_TIMEOUT = 3600
# Keep ModelBackend around for per-user permissions and maybe a local
# superuser.
AUTHENTICATION_BACKENDS = (
"django_auth_ldap.backend.LDAPBackend",
"django.contrib.auth.backends.ModelBackend",
)
Running an LDAP search from the cli works just fine
However when I try to authenticate with the http://localhost:8000/admin/ I get the following error.
The terminal on the other hand doesn't show anything:
There must be a better way to troubleshoot this, I have been at it all day and I can't figure it out.
add this in settings.py:
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {"console": {"class": "logging.StreamHandler"}},
"loggers": {"django_auth_ldap": {"level": "DEBUG", "handlers": ["console"]}},
}
logging

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")
)

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

Change Django Authentication Backend for Testing

My Django site uses the LDAP backend for authentication in production, but this is not suitable for testing (impossible to create requests from dummy users). How can I disable this backend, solely for tests?
Here is the relevant settings.py section:
AUTHENTICATION_BACKENDS = (
#'crowd.backend.CrowdBackend',
# 'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
AUTH_LDAP_SERVER_URI = "ldap://ldap.cablelabs.com"
import ldap
from django_auth_ldap.config import LDAPSearch
AUTH_LDAP_BIND_DN = "CN=CableLabs Internal,OU=cabletest,OU=Teamwork,OU=community,DC=cablelabs,DC=com"
AUTH_LDAP_BIND_PASSWORD = "UAq,0#ki"
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=community,dc=cablelabs,dc=com",ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)")
AUTH_LDAP_USER_ATTR_MAP = {"first_name": "givenName", "last_name": "sn","username":"sAMAccountName","email":"mail","photo":"thumbnailPhoto"}
AUTH_LDAP_CONNECTION_OPTIONS = {
ldap.OPT_REFERRALS: 0
}
If you only need/want to disable the backend for certain tests, you can also use the override_settings decorator. You can use this decorator on the test case class:
from django.test.utils import override_settings
#override_settings(AUTHENTICATION_BACKENDS=
('django.contrib.auth.backends.ModelBackend',))
class FooTest(TestCase):
def test_bar(self):
pass
But you can also selectively use it on a test method:
from django.test.utils import override_settings
class FooTest(TestCase):
#override_settings(AUTHENTICATION_BACKENDS=
('django.contrib.auth.backends.ModelBackend',))
def test_bar(self):
pass
Create an alternative settings file, for example myproj/test_settings.py, and specify that settings file when running unit tests.
Write the alternative settings file like this:
from myproj.settings import *
AUTHENTICATION_BACKENDS = (
#'your.ldap.backend',
'django.contrib.auth.backends.ModelBackend',
)
That is, the settings inherits everything from your regular settings, but overrides the AUTHENTICATION_BACKENDS definition, with your LDAP backend commented out.
Then, run your tests like this:
python manage.py test --settings=myproj.test_settings
For future reference, another option to look into for testing is to change the is_authenticated property of the User object to a lambda. For example:
user = User(...)
user.is_authenticated = lambda: True

django-social-auth error in connecting with Facebook

I have problem in connecting with Facebook backend of django-social-auth. I have created a Facebook app and in my project setting, I have provided its settings:
INSTALLED_APPS = (
...
'social_auth'
)
AUTHENTICATION_BACKENDS = [
"account.auth_backends.AuthenticationBackend",
'social_auth.backends.facebook.FacebookBackend',
'django.contrib.auth.backends.ModelBackend',
]
LOGIN_URL = "/"
LOGIN_REDIRECT_URLNAME = "home"
LOGOUT_URL = "/"
urlpatterns = patterns('',
...
url(r'', include('social_auth.urls')),
...
)
TEMPLATE_CONTEXT_PROCESSORS = (
...
'social_auth.context_processors.social_auth_by_type_backends',
)
SOCIAL_AUTH_EXPIRATION = 'expires'
FACEBOOK_APP_ID = '***************'
FACEBOOK_API_SECRET = '**************'
FACEBOOK_EXTENDED_PERMISSIONS = ['email', 'user_birthday', 'user_photos']
In 'Site Url' of my app on Facebook I have provided IP of my PC. Now when I connect with Facebook through my IP with my own account then it works fine. But when I try to connect with some other Facebook account then it give the error on permissions page:
"Sorry, something went wrong.We're working on getting this fixed as soon as we can."
Can someone has any idea?
In Facebook each app has certain permissions for Facebook Users, you are the lead developer, you can add testers and what not, Its on the app configuration interface.
For Facebook backend of django-social-auth to work properly then runserver on your IP instead of running on localhost.