Search code examples
djangodjango-allauth

Django allauth get credentials to make further requests on behalf of the user


I'm working on a Django project that requires user authentication for BitBucket, I have setup allauth such that users can authenticate with Bitbucket, I just don't understand how to make further requests to the Bitbucket API now that the user is authenticated.

I understand that allauth is purely for authentication purposes, there is just no documentation on how to access and make further use of the authentication, in this case accessing the credentials (oauth_token) such that I can make further requests on behalf of the resource-owner.


Solution

  • I found the authentication details to make a further requests.

    Workflow

    from allauth.socialaccount.models import SocialAccount, SocialApp
    
    bitbucket_app = SocialApp.objects.get(provider='bitbucket')
    user_account = SocialAccount.objects.get(user=request.user)
    # User should only have one SocialToken object per SocialApp
    # https://github.com/pennersr/django-allauth/blob/master/allauth/socialaccount/models.py#L137
    user_token = useraccount.socialtoken_set.first()
    
    # Credentials to make further requests
    client_key = bitbucket_app.client_id
    client_secret = bitbucket_app.secret
    resource_owner_key = user_token.token
    resource_owner_secret = user_token.token_secret
    

    Using credentials with requests and requests_oauthlib

    import requests
    from requests_oathlib import OAuth1
    auth = OAuth1(client_key, client_secret, resource_owner_key, resource_owner_secret)
    r = requests.get(protected_url, auth=auth)
    

    An example with the bitbucket-api

    https://bitbucket-api.readthedocs.org/en/latest/index.html

    from bitbucket.bitbucket import Bitbucket
    bb = Bitbucket(user_account.uid)  # Initialise with bitbucket username
    bb.authorize(client_key, client_secret, 'http://localhost', resource_owner_key, resource_owner_secret)
    # Get user repositories as an example
    bb.repository.all()