Tanvir Ahmmed
Tanvir Ahmmed

Reputation: 1

Django CORS request external redirect not allowed

I faced a problem during send GET request to a django view from react, and those view redirect to GOOGLE_AUTH_ENDPOINT., and this url hit a callback function. But after request from react, it give this error: Access to fetch at "google auth url" (redirected from 'localhost:8000') from origin 'localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

view

class Glogin(APIView):
    params = {
        'client_id': CLIENT_ID,
        'response_type': 'code',
        'scope': 'openid email profile',
        'redirect_uri': CALLBACK_DOMAIN,
        'state': state,
    }
    
    if APPS_DOMAIN:
        params['hd'] = APPS_DOMAIN
    
    def get(self,request):
        request.session['googleauth_csrf'] = state
        request.session['next'] = request.META.get('HTTP_REFERER', None)
        print('Here')
        print(urlencode(self.params))
        return HttpResponseRedirect("%s?%s" % (GOOGLE_AUTH_ENDPOINT, urlencode(self.params)))
        #data = {'link':GOOGLE_AUTH_ENDPOINT, 'params':self.params}
        #return Response(data)

ReactJs

  static GLogIn() {
    return fetch("http://127.0.0.1:8000/glogin/", {
      //method: "POST",
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
      //body: JSON.stringify(body),
    }).then((response) => response.json());
  }

URL

urlpatterns = [
    path('', include(router.urls)),
    path('auth/', obtain_auth_token),
    path('login/',views.LogInViewSet.as_view()),
    path('logout/',views.LogOutViewSet.as_view()),
    path('articles/',views.ArticlesView.as_view()),
    path('articles/<int:pk>/',views.ArticlesView.as_view()),
    path('glogin/',views.Glogin.as_view()),
    path('callback/',views.Callback.as_view(), name='googleauth_callback'),

    #path('articales/',views.ArticlesViewSet.as_view())
]

settings.py

CORS_ORIGIN_WHITELIST = (
    'localhost:3000',
    #'accounts.google.com',
    #'accounts.google.com/o/oauth2/v2'
    
)


CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]

Upvotes: 0

Views: 1478

Answers (1)

cbaxley
cbaxley

Reputation: 1

Put a hosts entry in the /etc/hosts file for 127.0.0.1

127.0.0.1 myfakedomain.local

Then add this to the CORS_ORIGIN_WHITELIST

'myfakedomain.local:8000',

Then you can access cors redirects. Chrome blocks them unless they are on special domains. Especially localhost.

Then send your browser to http://myfakedomain.local:8000

Upvotes: 0

Related Questions