Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate an AccessToken programmatically in Django?

I'm setting up an API. Everything is working. I'm creating a token via OAuth2 python lib. I'm using TastyPie for my API.

The problem I'm facing.. is that there is no "create" token method in the AccessToken or Client models.

I can create an accessToken via the Django admin, and I can create one by doing a curl to:

myhost.com/oauth2/access_token (with all the info, secret key, client id, user & pass)

my goal is to upon successful registration of a user with my API, the oAuth client is automatically created (working) but I also want to generate the AccessToken. I cannot cURL my own server as its giving me a redirect/connection refused error so I want to do it programmatically in Python. Anyway to do this? Here's a snippet:

try:
        user = User.objects.create_user(username, password)
        user.save()

        if user:
            oauth_client = Client(user=user, name="api account", client_type=1, url="http://example.com")
            oauth_client.save()

            oauth_client_id = oauth_client.pk
            oauth_client_secret = oauth_client.client_secret

        if oauth_client:
            print user
            print oauth_client_id
            print AccessToken.objects.all()
            print '........'
            token = AccessToken(user=user, client=oauth_client_id, scope=6)
            token.save()

the last two lines above, while giving NO errors.. will NOT save a new AccessToken.

like image 664
virtuexru Avatar asked Jul 25 '13 20:07

virtuexru


People also ask

How to create an accesstoken in Django?

I can create an accessToken via the Django admin, and I can create one by doing a curl to: myhost.com/oauth2/access_token (with all the info, secret key, client id, user & pass) my goal is to upon successful registration of a user with my API, the oAuth client is automatically created (working) but I also want to generate the AccessToken.

How do I create a token for a Django database migration?

The rest_framework.authtoken app provides Django database migrations. You'll also need to create tokens for your users. For clients to authenticate, the token key should be included in the Authorization HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings.

What is Token Authentication in Django rest?

Token authentication refers to exchanging username and password for a token that will be used in all subsequent requests so to identify the user on the server side.This article revolves about implementing token authentication using Django REST Framework to make an API.

How to manually create a token for a user?

Sometimes, you may wish to manually create a token for a user. This could be done as follows: The above function get_tokens_for_user will return the serialized representations of new refresh and access tokens for the given user. In general, a token for any subclass of rest_framework_simplejwt.tokens.Token can be created in this way.


3 Answers

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)
like image 179
Ugur Avatar answered Sep 18 '22 11:09

Ugur


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.

like image 43
waqasgard Avatar answered Sep 20 '22 11:09

waqasgard


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)
like image 45
twil Avatar answered Sep 17 '22 11:09

twil