使用 google oauth2 时的状态码 405

Posted

技术标签:

【中文标题】使用 google oauth2 时的状态码 405【英文标题】:Status Code 405 while using google oauth2 【发布时间】: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 应用程序凭据? 【参考方案1】:

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

【讨论】:

以上是关于使用 google oauth2 时的状态码 405的主要内容,如果未能解决你的问题,请参考以下文章

OAuth2.0 - 介绍与使用 及 授权码模式讲解

Google 通过 OAuth2 身份验证从 JavaScript 客户端联系 API 问题

OAuth2.0笔记

用户未经授权时的 Laravel 护照自定义错误消息和状态码

状态码 12501 使用 google 登录进行身份验证

在 ASP.NET Web Api 中测试 HttpClient 时的状态码 500