[Solved]-How to generate an AccessToken programmatically in Django?

9πŸ‘

I’m using https://github.com/caffeinehit/django-oauth2-provider. I managed to create access token and refresh token by using models. I might be bypassing grant flow.
I haven’t used this code in production but in development server i can perform API calls using the access token generated this way. I think it should be well tested before going to production.

#settings.py
OAUTH2_PROVIDER = {
# this is the list of available scopes
'SCOPES': {'read': 'Read scope'},
'ACCESS_TOKEN_EXPIRE_SECONDS': 36000,
} 

#views.py
expire_seconds = oauth2_settings.user_settings['ACCESS_TOKEN_EXPIRE_SECONDS']
scopes = oauth2_settings.user_settings['SCOPES']

application = Application.objects.get(name="ApplicationName")
expires = datetime.now() + timedelta(seconds=expire_seconds)
access_token = AccessToken.objects.create(
                user=user,
                application=application,
                token=random_token_generator(request),
                expires=expires,
                scope=scopes)

refresh_token = RefreshToken.objects.create(
                user=user,
                token=random_token_generator(request),
                access_token=access_token,
                application=application)

token = {
                'access_token': access_token.token,
                'token_type': 'Bearer',
                'expires_in': expire_seconds,
                'refresh_token': refresh_token.token,
                'scope': scopes}

return Response(token, status=200)
πŸ‘€Ugur

2πŸ‘

This is how I was able to make it work:

from oauth2_provider.views import TokenView
import json

class SuperUserLogin(views.APIView):
permission_classes = (permissions.AllowAny, )

def post(self, request, **kwargs):
    url, headers, body, status_code = TokenView().create_token_response(request)
    return Response(json.loads(body), status=status_code)

This is how my request object looks like.

{
"username" : email,
"password" : password,
"client_id" : client_id,
"client_secret" : client_secret,
"grant_type" : password

}

This generates the desired access_token. I’ve verified the token creation on my database.

πŸ‘€waqasgard

1πŸ‘

Based on what I see here https://github.com/caffeinehit/django-oauth2-provider/blob/master/provider/oauth2/views.py#L93 token creation is done this way

access_token = AccessToken.objects.create(
    user=user,
    client=client,
    scope=scope
)
RefreshToken.objects.create(
    user=user,
    access_token=access_token,
    client=client
)

I assume second token isn’t so interesting for you so it’s almost your code but with managers create() method. The only difference it makes is that manager calls save() with force_insert=True.

So try

token.save(force_insert = True)
πŸ‘€twil

0πŸ‘

I was able to get this to work in Django 1.6 using the following:

token = AccessToken.objects.create(user=user,
                                   client=Client.objects.get(name=clientName),
                                   scope=3)
πŸ‘€luny

0πŸ‘

Try below,

In [1]: import base64

In [2]: from django.conf import settings

In [3]: from django.http import HttpRequest

In [4]: from oauth2_provider.views import TokenView


In [5]: request = HttpRequest()

In [6]: key = base64.b64encode('{}:{}'.format(<CLIENT_ID>, <SECRET_KEY>))

In [7]: request.META = {'HTTP_AUTHORIZATION': 'Basic {}'.format(key)}

In [8]: request.POST = {'grant_type': 'password', 'username': '<USERNAME>', 'password': '<PASSWORD>'}

In [9]: tv = TokenView()

In [10]: url, headers, body, status = tv.create_token_response(request)

In [11]: body
Out [11]: '{"access_token": "IsttAWdao3JF6o3Fk9ktf2gRrUhuOZ", "token_type": "Bearer", "expires_in": 36000, "refresh_token": "y2KQyyliOuRIXf3q9PWzEUeBnx43nm", "scope": "read write"}'
πŸ‘€Parag Tyagi

0πŸ‘

Try this one, I just tested it moments earlier

>>> from oauth2_provider.models import Application
>>> app = Application.objects.create(name="Sample ORM", client_type="public", authorization_grant_type="password", user_id=1)
<Application: Sample ORM>
>>> import requests
>>> from requests.auth import HTTPBasicAuth
>>> 
>>> 
>>> data = "grant_type=password&username=admin&password=d3@narmada13"
>>> headers = {"content-type": "application/x-www-form-urlencoded"}
>>> r = requests.post(token_url, data=data, auth=(app.client_id, app.client_secret), headers=headers)
>>> print r.content
{"access_token": "5kEaw4O7SX6jO9nT0NdzLBpnq0CweE", "token_type": "Bearer", "expires_in": 7776000, "refresh_token": "ZQjxcuTSTmTaLSyfGNGqNvF3M6KzwZ", "scope": "read write"}
>>> import json
>>> json.loads(r.content)['access_token']
u'5kEaw4O7SX6jO9nT0NdzLBpnq0CweE'
>>> 

Leave a comment