07.01.2017       Выпуск 159 (02.01.2017 - 08.01.2017)       Статьи

Как реализовать свой способ авторизации для Django REST Framework

Читать>>



Экспериментальная функция:

Ниже вы видите текст статьи по ссылке. По нему можно быстро понять ссылка достойна прочтения или нет

Просим обратить внимание, что текст по ссылке и здесь может не совпадать.

How to Implement Custom Authentication with Django REST Framework

Introduction to Custom Authentication

Custom Authentication in Django REST Framework is the way you would create any time of authentication you would want. In fact, inside of the internals of DRF, you will find every other authentication scheme that I’ve talked about using CustomAuthentication. So, let’s look at an example of how you would implement something like this.

How to Implement Custom Authentication

WARNING: The example I’m about to show you is VERY VERY bad for security so DON’T use it in production. 🙂

First, you will need to override the BaseAuthentication class. It looks like this:

my_proj/accounts/auth.py from django.contrib.auth.models import User from rest_framework.authentication import BaseAuthentication from rest_framework import exceptions

class MyCustomAuthentication(BaseAuthentication):
    def authenticate(self, request):
        username = request.GET.get("username")

        if not username: # no username passed in request headers
            return None # authentication did not succeed

        try:
            user = User.objects.get(username=username) # get the user
        except User.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user') # raise exception if user does not exist

        return (user, None) # authentication successful

I called the new class MyCustomAuthentication. If you look at what this does, it retrieves a username as a GET request and will try to find a user with that username. (You should now understand why this is a stupid example).

Next, in settings.py you’ll want to update the DEFAULT_AUTHENICATION setting.

settings.py REST_FRAMEWORK = { ‘DEFAULT_AUTHENTICATION_CLASSES’: ( ‘accounts.auth.MyCustomAuthentication’, ), ‘DEFAULT_PERMISSION_CLASSES’: ( ‘rest_framework.permissions.IsAuthenticated’, ) }

And that is LITERALLY all you need to do to create a new authentication scheme. Download the custom code below and try going to the following URL:

http://localhost:8000/polls/api/questions/1/?username=chris

You should be able to see the data. Also, if you go to:

http://localhost:8000/polls/api/questions/1/

The authentication scheme should deny you from getting any data at all.

Click Here to Download the Sample Code

Homework

  1. Run the sample code and go to the two URLs above.
  2. Try to implement your own Session Authentication scheme WITHOUT enforcing CSRF tokens using Custom Authentication. You can see how Session Authentication is implemented here