1
votes

Because I'm mixing things up and just making myself more confused, maybe someone can actually guide me through it.

I need to make a Django REST API that requires login. However the User table already exists in a Postgres database. I think token-based authentication is most suitable, however, those tokens don't exist yet. (Login once to retrieve/create a token, check the token on each request)

  1. How can I use a POST request to submit login details purely for verifying the user?
  2. How would I generate a token upon successful login, and should I store it in a new Token table?
  3. After this, how can I use the token to provide authentication/authorization on API data requests?

All examples I can find use the default Django User model or don't go into enough detail, which I can't use in this case. I've made a custom authenticator that checks the username and password, however I can't get through the next steps.

from api.models import LogonAccount
from rest_framework import authentication
from rest_framework import exceptions
import bcrypt

class ExampleAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):

        username = request.data.get('username') # get the username request header
        password = request.data.get('password') # get the password request header
        if not username or not password: # no username or password passed in request headers
            return None # authentication did not succeed
        try:
            user = LogonAccount.objects.get(username=username)

            if bcrypt.hashpw(password.encode(), user.password.encode()):
                print("succes")
                return (user, None) # authentication successful
        except LogonAccount.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user')
1

1 Answers

1
votes

Don't get confused, you are simply trying to achieve token-based authentication with DRF. DRF already comes with this feature. This article will guide you through that https://simpleisbetterthancomplex.com/tutorial/2018/11/22/how-to-implement-token-authentication-using-django-rest-framework.html