RealmTeam / django-rest-framework-social-oauth2

python-social-auth and oauth2 support for django-rest-framework
MIT License
1.06k stars 191 forks source link

Handling standard auth-token along with social auth #128

Closed neon29 closed 7 years ago

neon29 commented 7 years ago

So far, I have been using the standard Django REST token-auth, while replacing the "Token" keyword by "Bearer" to have the same header as with the django-rest-framework-social-oauth2:

Authorization: Bearer my_token

So "my_token" can either be a Token from the auth-token table or an AccessToken returned by auth/convert-view.

To handle both authentications, I thus created the following class:

class ExampleAuthentication(TokenAuthentication):

    keyword = 'Bearer'

    def authenticate(self, request):

        token = request.META['HTTP_AUTHORIZATION']
        token = token[len(self.keyword) + 1 :]

        print(token)

        # Django auth-token
        try:
            tok = Token.objects.get(key=token)
            user = User.objects.get(id=tok.user_id)
            return user, None

        except:
            pass

        # social auth by means of DRSA2
        try:
            user = AccessToken.objects.get(token=token).user

            return user, None

        except:
            return None

While I manage to get any logged user registered with auth-token, when passing an AccessToken, to authenticate a social user (using Facebook), I always get AnonymousUser