0

I have been learning how to use djangorestframework token authentication using different blog posts and youtube videos. As for reference, I was following the blog here: https://chrisbartos.com/articles/how-to-implement-token-authentication-with-django-rest-framework/

I could not understand how are we going to check the token before accessing any page. I mean, I am developing an app, that exposes the todos a user creates through the rest framework. I have added a login that saves a user and returns the token created for that person. Now,I want to check that token to find the todos api that the person created and view it in my browser in a seperate url. As an example: Once I login through localhost:8000/api/v1/login, I should get the todos created by me at api/v1/todos in json rest api format. And if I go to api/v1/todos/1/, it should give me the details of the todo, as I have created in the serializers.

I would like to add some more info: So, say I have created a class for the login form. It will create a token for me. So the following is the login in the views:

    def signin(request):
        username = password = ''
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']

            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    return HttpResponse('Logged In')
            else:
                return HttpResponse('Wrong credentials')

        return render(request,'login.html')

So, I want to create a token for this. As mentioned in the djangorestframework documentation https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication it creates a seperate view for accessing the api-auth-token that is obtained from the function obtain_auth_token. But, how do I apply this function to save the token from current login in a class based view. Also, how do I pass this in another class based view, such that it shows no authentication in case I have not logged in but gives me the api in json when authenticated?

Phoenix
  • 373
  • 1
  • 4
  • 20

2 Answers2

0

https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication

Add rest_framework.authentication.TokenAuthentication to the DEFAULT_AUTHENTICATION_CLASSES in the REST_FRAMEWORK options in your Django settings.py file.

Add rest_framework.authtoken to your INSTALLED_APPS in settings.py

You can use the @authentication_classes decorator before the views you want to protect like so:

@authentication_classes((TokenAuthentication,))
def sample_function(request):

You'll also need to create tokens for your users, which is documented in that initial link.

Kon
  • 4,023
  • 4
  • 24
  • 38
0
class loginview(APIView):
   permission_classes = [
       permissions.AllowAny  # Anyone can Login
   ]

   def post(self,request):

      email_address = request.data.get('email')
      user_request = get_object_or_404(
        User,
        email=email_address,
      )
      username = user_request.username

      password = request.data.get("password")

      user = authenticate(username=username, password=password)
      id_u = user.id
      if not user:
          return Response({"error": "Login failed"}, 
                               status=status.HTTP_401_UNAUTHORIZED)

      token, _ = Token.objects.get_or_create(user=user)
      return Response({"token": token.key,'id':id_u})

Here is some sample code you can use to obtain Token while using the Login API From the App Frontend. Auth Token can be accessed from the Token model. Don't forget to add:

    from rest_framework.authtoken.models import Token

Also Add rest_framework.authtoken to installed apps in the settings.py

kae_screechae
  • 169
  • 12