在localhos上使用Google OAuth

2024-06-05 18:33:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我开始在Python和Django中使用OAuth。我需要它用于googleapi。我在本地主机上工作,因此无法注册用于url回调的域。我听说Google OAuth可以用于匿名域。找不到,我怎么做,在哪里做?

编辑:

我有这样的看法:

def authentication(request):
    CONSUMER_KEY = 'xxxxx'
    CONSUMER_SECRET = 'xxxxx'
    SCOPES = ['https://docs.google.com/feeds/', ]

    client = gdata.docs.client.DocsClient(source='apiapp')
    oauth_callback_url = 'http://%s/get_access_token' % request.META.get('HTTP_HOST')
    request_token = client.GetOAuthToken(
      SCOPES, oauth_callback_url, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET)
   domain = '127.0.0.1:8000'
   return HttpResponseRedirect(
        request_token.generate_authorization_url(google_apps_domain=domain))

这个错误:

Sorry, you've reached a login page for a domain that isn't using Google Apps. Please check the web address and try again.

通过https://code.google.com/apis/console/注册

编辑:

CONSUMER_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
CONSUMER_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
SCOPES = ['https://docs.google.com/feeds/', ]
DOMAIN = 'localhost:8000'


def authentication(request):    
    client = gdata.docs.client.DocsClient(source='apiapp')
    oauth_callback_url = 'http://%s/get_access_token' % DOMAIN

    request_token = client.GetOAuthToken(SCOPES,
                                     oauth_callback_url,
                                     CONSUMER_KEY,
                                     consumer_secret=CONSUMER_SECRET)

    return HttpResponseRedirect(
        request_token.generate_authorization_url())


def verify(request):
    client = gdata.docs.client.DocsClient(source='apiapp')
    f = open('/home/i159/.ssh/id_rsa')
    RSA_KEY = f.read()
    f.close()

    oauth_callback_url = 'http://%s/get_access_token' % DOMAIN

    request_token = client.GetOAuthToken(SCOPES,
                                     oauth_callback_url,
                                     CONSUMER_KEY,
                                     rsa_private_key=RSA_KEY)
    return HttpResponseRedirect(
        request_token.generate_authorization_url(google_apps_domain=DOMAIN))

错误:

Unable to obtain OAuth request token: 400, Consumer does not have a cert: xxxxxxxxxxxxxxx.apps.googleusercontent.com


Tags: keycomclienttokenurldocsgetsecret
3条回答

尝试不带参数的代码:

return HttpResponseRedirect(request_token.generate_authorization_url())

为了清楚起见,在OAuth 1.0或OAuth 2.0上开发时,可以将web应用程序流与localhost一起使用。OAuth 2.0应该是首选的,因为它是我们关注的机制。OAuth 2.0的用户体验将大大提高。

没有什么可以阻止您使用localhost作为回调URL。我一直都是自己做的。您只需要确保回调URL完全匹配,包括任何端口号,并且由于明显的原因,您不能以这种方式部署应用程序。安装的应用程序更加复杂,但是如果您正在使用Django执行某些操作,则可以利用OAuth 2.0是承载令牌系统这一事实。只要保持刷新令牌服务器端,就可以在带外对自己的应用程序进行身份验证,然后将承载令牌发送到已安装的应用程序。安装的应用程序将有大约一个小时的窗口,在需要重复此过程之前可以在其中进行调用。这在大多数情况下对用户都是透明的。承载令牌的传输应该在加密通道上进行。

OAuth 1.0 for Installed Applications

除此之外,您可能不想在示例代码中包含实际的CONSUMER_KEYCONSUMER_SECRET

相关问题 更多 >