LDAP authentication isnt happening over django rest API - python

I am authenticating users who login against through django REST framework against NIS using pythonPAM . But when I make the changes to settings.py as mentioned below, user credentials isnt being verified against LDAP.
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
)
This along with ldap credentials for binding is used.
Note: I can connect to LDAP server and get all teh details. Its only a problem with django restframework.
I also tried
AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.RemoteUserBackend',]
and it did not work.
Currently in my urls.py, I call url(/login,) endpoint and authenticate against NIS server. How do I change it to LDAP?
I am new to django and need help on this.

Related

Python allauth disable mail confirmation for oauth apps

I'm new into python and django and I'm developing an app liked to a django server that works as oauth provider.
I've set this on settings.py file:
ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https'
ACCOUNT_EMAIL_VERIFICATION = 'none'
ACCOUNT_EMAIL_REQUIRED = True
But if I did not add the verified flag on the mail section in django I cannot login into the app.
What should I do in order to remove the verification step?
remove those tree lines and paste this, I hope it works
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

Sending users a password insertion Django Rest Framework

I am using Django Rest Framework and want to be able to send a user a password reset view. It actually comes from a user inviting them into the software but it automatically sets a secure password.
I want to be able to send that user an email asking them to change their password.
How can I go about this?
you need to use builtin apps in django for password reset you need to use it on ur urls.py
for example:
in settings.py
INSTALLED_APPS = [
...
'password_reset',
...
]
urls.py in project:
path('',include('django.contrib.auth.urls')),
in app urls.py:
path('password_reset/', include('password_reset.urls')),

Django_hosts Not Working With Django's Default Authentication

I'm using this package called django_hosts to re-route urls for some apps.
Everything is working fine except for the fact that django_hosts is not working with Django Authentication.
I hosted this url api.example.com, so on this page with the url api.example.com:8000/add_post, I want users to add post but before doing that you must be authenticated. So after I logged in, I still can't submit post via the form talkless of posting. But when I go back to example.com, it shows that I'm logged in but api.example.com is telling me otherwise.
How do I make django authentication work with this package?
The problem is that the authentication token is hooked to the domain. Using Django's default configuration, the api.example.com can't access the example.com auth token.
You can change this behaviour by setting the SESSION_COOKIE_DOMAIN configuration in your settings.py module:
SESSION_COOKIE_DOMAIN = 'example.com'
But not too fast! Do it carefully, otherwise you can break your application:
Be cautious when updating this setting on a production site. If you
update this setting to enable cross-domain cookies on a site that
previously used standard domain cookies, existing user cookies will be
set to the old domain. This may result in them being unable to log in
as long as these cookies persist.
More info on the official documentation.

django with apache ldap backend auth, get logged in username and ldap group & hide detail based on group (mod_ldap)

im using Django with Apache and LDAP backend auth, my http conf is as below:
LoadModule ldap_module modules/mod_ldap.so
LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
#
<Location />
AuthName "Please enter your domain credentials."
AuthBasicProvider ldap
AuthType basic
AuthLDAPUrl "ldap://example.com:389/DC=example,DC=com?sAMAccountName"
AuthLDAPBindDN "CN=serv,OU=Service Accounts,DC=example,DC=com"
AuthLDAPBindPassword XXXX
AuthLDAPBindAuthoritative off
LDAPReferrals off
Require valid-user
</Location>
Which when i now load my site i get a basic auth prompt which is great, what id like to be able to do now is to receive the logged in username, ive searched and tried a few things such as:
LoggedInUser = request.user.username
which gives me a request is not defined message (i have import requests at the top)
LoggedInUser = os.getenv["REMOTE_USER"]
which gives me TypeError: 'function' object has no attribute 'getitem'
does anyone know what i need to be using?
i also need to hide certain urls from users if they are not in the correct ldap group, so would need to get the users AD groups aswell from the session
Thanks
Per request WSGI environ key/values are found in Django request.META object. Thus try:
request.META['REMOTE_USER']
Whether what Apache passes through to you is in format you expect is a different issue. You may find what you want in other variables passed through. See:
http://httpd.apache.org/docs/2.4/mod/mod_authnz_ldap.html#exposed
According to the documentation topic "Authentication using REMOTE_USER", in order to use Apache authentication, you must include a specific middleware:
Configuration
First, you must add the django.contrib.auth.middleware.RemoteUserMiddleware to the MIDDLEWARE_CLASSES setting after the django.contrib.auth.middleware.AuthenticationMiddleware:
MIDDLEWARE_CLASSES = [
'...',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.RemoteUserMiddleware',
'...',
]
Next, you must replace the ModelBackend with RemoteUserBackend in the AUTHENTICATION_BACKENDS setting:
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.RemoteUserBackend',
]
If you are already doing this without success, and given you need more granular access controls, I would just write a custom authentication backend and ditch mod_ldap altogether. Writing a custom authentication backend is really easy. The key is to get the python ldap module working before writing the backend.
In order to access request.user you must be inside a Django view. For example:
def index(request):
user = request.user
return render(request, 'template.html', {"user": user})
And in the template.html file:
<h1>Hi, {{ user }}</h1>

Django OAuth 2 client setup - client isn't recognizing tokens

I attempting to use the Django OAuth Toolkit in a project I'm working on. I've set up two servers - one as the OAuth provider and another as a client service that is accessed only by authenticated users.
The OAuth provider seems to be working just fine. I'm able to create a link on the client service that directs to the OAuth provider. The user then logs in, and is prompted whether to allow/deny the application. If the user allows the application, the user is then redirected back to the client service, and the URI contains the access token. Because this service needs to be accessible from both a website and a mobile client, I'm using an implicit grant, and following this way of doing things: https://aaronparecki.com/articles/2012/07/29/1/oauth2-simplified#browser-based-apps.
Everything with the provider seems to work as expected, but I'm having issues with the client service app, which is also a Django application. It doesn't appear to recognize the token in the redirect URI, and as a result I'm unable to make any authenticated requests against the service.
I've made the following changes to the client service's settings.py:
I've added the AUTHENTICATION_BACKENDS section, as follows:
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'oauth2_provider.backends.OAuth2Backend',
)
I've added oauth2_provider.middleware.OAuth2TokenMiddleware to the MIDDLEWARE_CLASSES section.
I've added oauth2_provider to the INSTALLED_APPS.
The REST_FRAMEWORK section now looks like:
REST_FRAMEWORK = {
'DEFAULT_MODEL_SERIALIZER_CLASS':
'rest_framework.serializers.HyperlinkedModelSerializer',
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
}
I've also added the OAUTH_PROVIDER section:
OAUTH2_PROVIDER = {
# this is the list of available scopes
'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'}
}
As near as I can figure, there must be something else that I'm missing in my settings.py that will tell Django to look for the token, but I'm at a bit of a loss on what this might be.
Can someone point me in the right direction on what I might be missing here?
EDIT: I should clarify the results I'm getting when attempting to call something on the client service. When I make a curl request to the client service, like so (except with real values plugged in):
curl -H "Authorization: Bearer token_goes_here" https://service.com/api/some_api/call
I get a result of:
{"detail": "Authentication credentials were not provided."}
It's as if the client service isn't looking in the right place for the credentials, which makes me think that something isn't set up quite right.
DEFAULT_PERMISSION_CLASSES IsAuthenticated for REST_FRAMEWORK is blocked non auth requests.
If you planned using javascript to access your REST API see https://github.com/evonove/django-oauth-toolkit/blob/master/oauth2_provider/tests/test_implicit.py
For "Implicit Grant Flow" you must:
login via ModelBackend with user login and password.
create oauth2 application ( /o/applications/ )
or from django console, see test.
get auth token from "/o/authorize/" url with logged in user.
then you must add token to "'HTTP_AUTHORIZATION': 'Bearer ' + access_token," header, to access API resourses.
And, i think, at this workflow we do not need auth_backends and middleware because we have DEFAULT_AUTHENTICATION_CLASSES in REST_FRAMEWORK.
All grant types you can see in DOT based on lib
https://oauthlib.readthedocs.org/en/latest/oauth2/grants/grants.html
Or you can use more simplest "Resource owner password-based" as in DOT documentation described...

Categories

Resources