24👍
This has been added to the Django 1.3 release. See more current documentation for this here:
http://docs.djangoproject.com/en/dev/howto/auth-remote-user/
40👍
For just supporting basic auth on some requests (and not mucking with the web server — which is how someone might interpret your question title), you will want to look here:
- [Django]-How to upload multiple images to a blog post in django
- [Django]-ModuleNotFoundError: No module named 'grp' on windows
- [Django]-What is the clean way to unittest FileField in django?
10👍
Do check out Oli’s links. You basically see the authenticated username as verified by Basic HTTP Authentication in Django by looking at request.META[‘REMOTE_USER’].
Update: Tested the proposed patch for ticket #689, which is available up-to-date in telenieko’s git repository here. It applies cleanly at least on revision 9084 of Django.
Activate the remote user authentication backend by
- adding the
RemoteUserAuthMiddleware
afterAuthenticationMiddleware
- adding the setting
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.RemoteUserAuthBackend',)
If you use lighttpd and FastCGI like I do, activate mod_auth, create credentials for a test user (I called it testuser
and set 123
as the password) and configure the Django site to require basic authentication.
The following urls.py
can be used to test the setup:
from django.conf.urls.defaults import *
from django.http import HttpResponse
from django.contrib.auth.models import User
urlpatterns = patterns('',
url(regex='^$',
view=lambda request: HttpResponse(repr(request), 'text/plain')),
url(regex='^user/$',
view=lambda request: HttpResponse(repr(request.user), 'text/plain')),
url(regex='^users/$',
view=lambda request: HttpResponse(
','.join(u.username for u in User.objects.all()),
'text/plain')),
)
After reloading lighty and the Django FCGI server, loading the root of the site now asks for authentication and accepts the testuser
credentials, and then outputs a dump of the request object. In request.META these new properties should be present:
'AUTH_TYPE': 'Basic'
'HTTP_AUTHORIZATION': 'Basic dGVzdHVzZXI6MTIz'
'REMOTE_USER': 'testuser'
The /user/
URL can be used to check that you’re indeed logged in as testuser
:
<User: testuser>
And the /users/
URL now lists the automatically added testuser
(here the admin
user I had created when doing syncdb
is also shown):
admin,testuser
If you don’t want to patch Django, it’s trivial to detach the RemoteUserAuthBackend
and RemoteUserAuthMiddleware
classes into a separate module and refer to that in the Django settings.
- [Django]-Django data migration when changing a field to ManyToMany
- [Django]-Generate unique id in django from a model field
- [Django]-Get protocol + host name from URL
5👍
Yes you can use basic autorization with django as something similar:
def post(self, request):
auth_header = request.META.get('HTTP_AUTHORIZATION', '')
token_type, _, credentials = auth_header.partition(' ')
import base64
expected = base64.b64encode(b'<username>:<password>').decode()
if token_type != 'Basic' or credentials != expected:
return HttpResponse(status=401)
authorization success flow code ...
request.META contains key HTTP_AUTHORIZATION in which your Autorization is present.
In case if you are using apache with modWSGI, the key HTTP_AUTHORIZATION might not be present. You need to add below line in your WSGI config
WSGIPassAuthorization On
Refer this detailed answer:
Passing apache2 digest authentication information to a wsgi script run by mod_wsgi
Hope it is useful for someone who is wondering why HTTP_AUTHORIZATION key is not present
- [Django]-Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries
- [Django]-Django REST Framework: adding additional field to ModelSerializer
- [Django]-How to force Django models to be released from memory
3👍
There is httpauth.py. I’m still a complete newb with Django so I’ve no idea how it fits in exactly, but it should do what you’re looking for.
Edit: here’s a longer bug thread on the subject.
- [Django]-Silence tqdm's output while running tests or running the code via cron
- [Django]-How to add multiple arguments to my custom template filter in a django template?
- [Django]-Django Rest Framework: Access item detail by slug instead of ID
0👍
Because django can be run in several ways, and only modpython gives you close integration with Apache, I don’t believe there is a way for django to log you in basic on Apache’s basic auth. Authentication should really be done at the application level as it’ll give you much more control and will be simpler. You really don’t want the hassle of sharing a userdata between Python and Apache.
If you don’t mind using a patched version of Django then there is a patch at http://www.djangosnippets.org/snippets/56/ which will give you some middleware to support basic auth.
Basic auth is really quite simple – if the user isn’t logged in you return a 401 authentication required status code. This prompts the browser to display a login box. The browser will then supply the username and password as bas64 encoded strings. The wikipedia entry http://en.wikipedia.org/wiki/Basic_access_authentication is pretty good.
If the patch doesn’t do what you want then you could implement basic auth yourself quite quickly.
- [Django]-How do I use Django groups and permissions?
- [Django]-How to make two django projects share the same database
- [Django]-Equivalent of PHP "echo something; exit();" with Python/Django?
0👍
This seems to be a task for custom AuthenticationBackend
– see Django documentation on this subject, djangosnippets.org has some real-life examples of such code (see 1 or 2) (and this is not really a hard thing).
AuthenticationBackend
subclasses have to have only 2 methods defined and their code is pretty straightforward: one has to return User object for user ID, the second has to perform credentials check and return User object if the credentials are valid.
- [Django]-Parsing unicode input using python json.loads
- [Django]-Unsupported operand type(s) for *: 'float' and 'Decimal'
- [Django]-Filtering dropdown values in django admin