【问题标题】:Status Code 405 while using google oauth2使用 google oauth2 时的状态码 405
【发布时间】:2018-02-25 11:35:33
【问题描述】:

我正在使用带有 Angular JS 的 Django 来访问 Google Drive API。我正在关注来自 Google 的 this 文档。 FLOW.step1_get_authorize_url() 给了我类似于页面上提到的示例 URL 的 URL。但是问题是return HttpResponseRedirect(authorize_url)之后浏览器并没有重定向到authorize_url,报错如下图(Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access. The response had HTTP status code 405)。

但如果我复制粘贴 URL,它就可以正常工作。

oauth2 函数如下所示。

def index(request):

    FLOW = flow_from_clientsecrets(
        settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON,
        scope='https://www.googleapis.com/auth/drive',
        redirect_uri='http://127.0.0.1:8000/oauth2callback/'
    )
    FLOW.params['access_type'] = 'offline'
    authorize_url = FLOW.step1_get_authorize_url()
    return HttpResponseRedirect(authorize_url)

这里是 oauth2callback 函数。

def auth_return(request):
    credential = FLOW.step2_exchange(request.GET)
    return HttpResponseRedirect("/mycustomurl")

我使用this 在 Django 服务器端启用 CORS。这是我在 Angular 中调用 oauth2 的服务部分。

(function () {

    'use strict';

    angular.module('myApp')
    .service('myService', function ($http) {

        this.saveToDrive = function (startYear, endYear, shape) {
            var config = {
                    params: {
                        start: '1999',
                        end: '2002',
                        action: 'download-to-drive'
                    },
                    headers: {
                        'Access-Control-Allow-Origin': '*',
                        'X-Requested-With': null
                    }
            }

            var promise = $http.get('/oauth2/', config)
            .then(function (response) {
                return response.data;
            });
            return promise;
        };

    });

})();

请建议我在这里缺少什么。非常感谢任何帮助或建议。

【问题讨论】:

  • 您在settings 中添加了CORS_ORIGIN_ALLOW_ALL=TrueCORS_ORIGIN_WHITELIST=('127.0.0.1:8000', ) 吗?
  • 根据 doc (docs.djangoproject.com/en/1.11/ref/settings/#allowed-hosts) - 当 DEBUG 为 True 且 ALLOWED_HOSTS 为空时,将根据 ['localhost', '127.0.0.1', '[::1]'] 验证主机.我已将 DEBUG 设置为 True。
  • 对。我删除了那条评论。我不是故意问这个的。请查看更新的。
  • 是的,我的设置中有CORS_ORIGIN_WHITELIST = ('127.0.0.1:8000',)
  • 您是否在 Google API 控制台的 Authorized Javascript Origins 中添加了“127.0.0.1:8000”作为 OAuth2 的 Web 应用程序凭据?

标签: angularjs django google-oauth http-status-code-405


【解决方案1】:

我发现这是一个次要的设计问题,而不是代码问题。我分离了向客户端发送 oauth2 请求的逻辑,在 oauth2 请求之后,我使用 params 选项向内部 API 发送请求。现在它工作正常。

【讨论】:

    猜你喜欢
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    相关资源
    最近更新 更多