Andrei Moiseev
Andrei Moiseev

Reputation: 4084

Auth token in URL path

I'm using Django REST Framework TokenAuthentication.

For a few URLs I'm constrained to having to include the token in the URL path:

https://example.com/api/<auth_token>/something

So the urlpatterns are:

urlpatterns = [
    path('api/<auth_token>/something', views.SomeView.as_view()),
]

And the view is:

class SomeView(APIView):
    authentication_classes = (TokenAuthentication)
    permission_classes = (IsAuthenticated, )

    def get(self, request, auth_token):
    ...

But TokenAuthentication does not work here because the token is in the URL path, not in the header. I'd like to extend TokenAuthentication to handle in-URL tokens too, if possible.

Upvotes: 0

Views: 1308

Answers (1)

gmc
gmc

Reputation: 3990

First of all, putting auth tokens in the url is insecure and not recommended (urls end up in server logs and stuff).

If it was a matter of life or death, what I would do is extend the TokenAuthentication class from Django rest, overriding only the authenticate method. If you look at the source code, it obtains the token from the header, runs some validations and calls self.authenticate_credentials(token). So I'd do something like:

class UrlTokenAuthentication(TokenAuthentication):
    def authenticate(self, request):
        token = # get the token from the url path and check that has proper format, etc.
        return self.authenticate_credentials(token)

Upvotes: 1

Related Questions