Search code examples
angularjsdjangogoogle-oauthhttp-status-code-405

Status Code 405 while using google oauth2


I am using Django with Angular JS to access the Google Drive API. I am following this document from Google. The FLOW.step1_get_authorize_url() gives me the URL similar to the sample URL mentioned on the page. But the problem is that after return HttpResponseRedirect(authorize_url) the browser does not redirect to the authorize_url and gives the error as shown in the picture below (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).

enter image description here

But if I copy pasted the URL, it works fine.

The oauth2 function looks like this.

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)

And here is the oauth2callback function.

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

I used this to enable CORS in the Django Server Side. Here is my part of service in Angular that makes the call to 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;
        };

    });

})();

Please suggest what am I missing here. Any help or suggestions are highly appreciated.


Solution

  • I found it be a minor design issue rather than the code issue. I separated the logic that sends the oauth2 request to the client, and after the oauth2 request, I sent request to internal API with the params options. And now it's working fine.