2013-07-25 32 views
7

好吧,我正在设置一个API。一切正常。我通过OAuth2 python lib创建了一个令牌。我为我的API使用TastyPie。如何在Django中以编程方式生成AccessToken?

我面临的问题是,AccessToken或Client模型中没有“创建”令牌方法。

我可以通过Django管理创建的accessToken,我可以做一个卷曲创建一个:

myhost.com/oauth2/access_token(与所有的信息,密钥,客户端ID,用户&通)

我的目标是在与我的API用户成功注册后,OAuth客户端会自动创建(工作),但我也想生成的accessToken。我无法控制我自己的服务器,因为它给了我一个重定向/连接拒绝错误,所以我想在Python中以编程方式执行它。无论如何要做到这一点?这里有一个片段:

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://mysite.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() 
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://mysite.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() 

上面的最后两行,同时给没有错误..不会保存一个新的AccessToken。有任何想法吗?谢谢StackOverflow !!!!

+0

什么确切的图书馆时刻? http://hiidef.github.io/oauth2app/或https://code.google.com/p/django-oauth2/或其他一些? – twil

+0

https://github.com/caffeinehit/django-oauth2-provider < - 这一个。我通过PIP(django-oauth2-provider == 0.2.6)安装它。是这个问题,我使用了错误的库吗? – virtuexru

+0

不是错的。他们都一样,但有点不同;)。 – twil

回答

0

基于我在这里看到的https://github.com/caffeinehit/django-oauth2-provider/blob/master/provider/oauth2/views.py#L93令牌创建完成这样

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

我认为第二个令牌是不适合你那么有趣所以它几乎是你的代码,但与管理者create()方法。它使唯一的区别是,经理叫save()force_insert=True

所以尽量

token.save(force_insert = True) 
+0

谢谢您的回应!所以我之前尝试过(使用AccessToken.objects。create()而不是.save(force_insert = True)。我认为它会做的伎俩,但它仍然不插入令牌。其他一切正常。我没有使用你的代码,但没有数据库插入任何错误。让我拉我的头发的东西是我可以通过Django中的管理面板创建一个令牌! :( – virtuexru

+0

我认为问题可能是我需要首先获得'grant'才能获得access_token,但我不确定,我会做更多的阅读:| – virtuexru

+0

这很奇怪,因为在保存之前没有额外的检查。 '对象这里https://github.com/caffeinehit/django-oauth2-provider/blob/master/provider/views.py#L459仅用于获取用户和范围。但愿这是你使用的数据库路由器? – twil

0

我能得到这个在Django 1.6工作中使用下列内容:

token = AccessToken.objects.create(user=user, 
            client=Client.objects.get(name=clientName), 
            scope=3) 
7

我使用https://github.com/caffeinehit/django-oauth2-provider。我设法通过使用模型创建访问令牌和刷新令牌。我可能会绕过授权流程。 我还没有使用这个代码在生产,但在开发服务器,我能使用这种方式生成的访问令牌API调用。我认为在投入生产之前应该进行充分测试。

#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) 
+0

这基本上与oauth-toolkit一起工作。 – owenfi

+0

嗨,有没有什么办法可以在用户频繁请求令牌时发送未过期的访问令牌?到目前为止,它创建了多个令牌,而不是返回相同的值!!!!!需要解决方案 – Tommy

+0

单个访问令牌有一个参数(https://django-oauth2-provider.readthedocs.org/en/latest/api.html#provider.constants.SINGLE_ACCESS_TOKEN),但我认为它不适用于本手册方法。您可以检查用户是否有有效的访问令牌并返回相应的令牌。 – Ugur

0

下面尝试,

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"}' 
0

试试这个,我只是测试它,你用前面

>>> 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&[email protected]" 
>>> 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' 
>>>