LDAP authentication with django REST - python

Currently I have basic authorization on for visting the Django REST Api backend and I can use the username / passowrd which was created via shell
I don't have login page for that I am using all that is built in.
Now i want to authenticate the username /password from LDAP from my Active Directory.
Is there any way that I don't need to create Login page for that and I can enter the username / password on same place and my user authenticates with Active Directory.
Do I need to create some manual logic of getting username password and then postig it, I was thinking if I can get it without doing that stuff like basic authentication which django already provides

There is a package called django-auth-ldap.
It comes with a django authentification backend.
Just add django_auth_ldap.backend.LDAPBackend to your AUTHENTICATION_BACKENDS
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
You probably have to define a few more settings like you ldap host. But the documentation is quite good.
Then you can use your normal authentication views and django "decide" which method to use. There is more information in the django docs

Related

Django send authenticated user to another django server with the same db

I know question sounds strange, I will explain it here.
I have two Django servers which share the same DB. One is a light front/back server and the order one takes the heavy computing part. They share the same database.
I am currently securing the web, and I have a couple of views in the light server requiring user login:
#login_required()
#permission_required('auth.can_upload', login_url='/accounts/login/')
This works nicely in the light server since the user is authenticated (request.user returns a valid user in the views).
The problem comes when I have to send the uploaded data to the other server since it is protected as I showed earlier, I do not know how to pass it the user that is already logged (user is valid since servers share the DB).
# send an upload request using requests
s = requests.Session()
r1 = s.get(upload_process_url)
csrf_token = r1.cookies['csrftoken']
a = s.post(upload_process_url, files=request.FILES,
data={'csrfmiddlewaretoken': csrf_token},
headers=dict(Referer=upload_process_url))
I cannot ask every time the user and password or save them. The thing is I want to pass the user that is already logged in a request.
The user was logged using the default django accounts/login page and authentication.
Any clues and what could I try? I think this problem cannot be as difficult as it looks to me. I just want to send an authenticated request. If I remove the decorators everything works nicely with this code
Thanks a lot
Have a look at REMOTE_USER authentication:
This document describes how to make use of external authentication sources (where the Web server sets the REMOTE_USER environment variable) in your Django applications. This type of authentication solution is typically seen on intranet sites, with single sign-on solutions such as IIS and Integrated Windows Authentication or Apache and mod_authnz_ldap, CAS, Cosign, WebAuth, mod_auth_sspi, etc.
Basically your "light" server does the authentication as it already does. When you are doing a request to your "heavy" server, you should set a Auth-User header containing the username of your user. Django will then automatically authenticates the corresponding user.
By default, Django will read an environment variable set by an authentication server. But we can make it work with a HTTP header instead:
# middlewares.py
from django.contrib.auth.middleware import RemoteUserMiddleware
class CustomHeaderMiddleware(RemoteUserMiddleware):
header = 'HTTP_AUTH_USER'
# settings.py
MIDDLEWARE = [
'...',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'my_project.middlewares.CustomHeaderMiddleware',
'...',
]
Then, you can do something like this then in your request (assuming you have your Django user at hand):
s = requests.Session()
r1 = s.get(upload_process_url)
a = s.post(
upload_process_url,
files=request.FILES,
headers={
'Auth-User': user.username,
},
)
Since you're not doing a request from a browser, you can avoid the CSRF protection by marking the called "heavy" view with #csrf_exempt decorator (as you found yourself).
Be careful though that your "heavy" server should not be accessible directly on the internet and always behind a proxy/VPN accessible only by your "light" server.

Integrate python-social-auth (social-app-django) to be used with the Django admin

I want to create an app that uses the django admin, but allows logins via google (my company google account) in place of the django default ModelAdmin.
Currently, it looks like social-app-django (google) is the way to go, but after having installed and setup a project, it's not clear to me how I can allow django admin logins to use the social-app-django authentication. I've attempted to configure my project as described here http://python-social-auth.readthedocs.io/en/latest/configuration/django.html but it isn't clear how this can be integrated with the django admin.
I found this snippit (which seems out-of-date), and added it, but get a 404 when I try to goto /admin/:
Page not found (404) Request Method: GET Request
URL: http://127.0.0.1:8000/accounts/login/?next=/admin/login/%3Fnext%3D/admin/
Using the URLconf defined in telos.urls, Django tried these URL
patterns, in this order: ^login/(?P[^/]+)/$ [name='begin']
^complete/(?P[^/]+)/$ [name='complete']
^disconnect/(?P[^/]+)/$ [name='disconnect']
^disconnect/(?P[^/]+)/(?P[^/]+)/$
[name='disconnect_individual'] ^admin/ The current path,
accounts/login/, didn't match any of these.
If I remove the snippit, /admin/ will redirect to /admin/login/ and on login attempt return the ERROR text:
Please enter the correct username and password for a staff account.
Note that both fields may be case-sensitive.
In addition to the configuration, I've added the following to my settings.py:
projects/models.py (MyUser)
from django.contrib.auth.models import AbstractUser
class MyUser(AbstractUser):
pass
settings.py
# for identification of SOCIAL_AUTH_USER
# http://python-social-auth.readthedocs.io/en/latest/configuration/settings.html#user-model
SOCIAL_AUTH_USER_MODEL = 'projects.MyUser'
AUTH_USER_MODEL = 'projects.MyUser' # not sure if this is needed
Can anyone direct me on how I can setup my project to allow me to login to the django admin through social-app-django (google)?
Django Admin uses the auth contrib application, so any authentication process triggers the same mechanism than a user logging in to a non-admin section and it will be processed by python-social-auth backends if they are defined in AUTHENTICATION_BACKENDS setting.
In order to make it work you will need to:
Add a Login with Google link (linking to /login/google-oauth2) to the login form. You can override the default login form by adding a admin/login.html template or by defining a custom AdminSite
Ensure that the user is flagged as is_staff, otherwise access to the admin will be forbidden.

Django-social-auth extended facebook permissions like spotify

I was able to get the publish_actions permission for my facebook app by using this setting
FACEBOOK_EXTENDED_PERMISSIONS = ['publish_actions']
The problem is that when authorizing my facebook app is that a second window is used to prompt the user to allow my app to publish actions after the initial prompt for the basic info.
How can I use only one window to get users to authorize my app? I'm trying to get my authorization window to look similar spotify's authorization
Django-social-auth has been superseded by python-social-auth. In python-social-auth, you define extended permission by using SOCIAL_AUTH_FACEBOOK_SCOPE inside settings.py. For example:
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'user_photos']
It will only show a single authorization dialog.

GAE and django same users

I'm running a GAE and Django helper project and i ran into some issues when creating a User from de django shell. After exploring the code under the helper directory i came across with the following code:
class User(BaseModel):
user = db.UserProperty(required=True)
My question is, do i have to bind the django user to a google account if so, how do i create a django or google user from my code?
UPDATE: I meant to say create the account without having the google account itself. For instace not having:
users.get_current_user()
UPDATE: A user must be able to create a new account just like regular django users, with a register page for that matter.
For AppEngine, you can get the users who are logged into your application.
from google.appengine.api import users
And then you do
username = users.get_current_user()
And set your user property
User(user=username)
You could lookup the tutorial on how to do redirect to login to ask the application to login to get the user.

Django request.user is empty

Using django, I am authenticating the user through Google. I get the initial request tokens & redirect the user to google for auth. After which google redirects the user back to my website (using the redirect_url I provide).
At this point the request.user.id is None so is request.user.username why is this happening? I need the user ID to enter the access_tokens (that google sends me) into the DB.
Under what conditions can request.user object in Django be empty?
UPDATE1: When I get redirected back from Google with the url pattern as http://mywebsite.com/lserv?s=goog control comes back to my django views function, but django gives me the request.user object user as Anonymous user with no username or id. why?
UPDATE2:
all this is running on python manage.py runserver for now...
UPDATE3: Anybody faced anythn similar to this? basically, out of no reason the user in request clears out automatically & I get assigned as Anonymous user. All this happens between url requests from the user (from browser). Why?
Django's auth mechanism has nothing to do with Google's or any other auth service. If you want to integrate third party auth service with your Django site, you should do it youself.
If you're using oauth2 library, it's README has a section named "Logging into Django w/ Twitter" may help you.
If you are using oauth api from google. To get the user you have to do something like this
from google.appengine.api import oauth
# ...
try:
# Get the db.User that represents the user on whose behalf the
# consumer is making this request.
user = oauth.get_current_user()
except oauth.OAuthRequestError, e:
# The request was not a valid OAuth request.
# ...

Categories

Resources