2016-02-12 2 views
1

У меня проблема в Google+ OAuth с использованием рамки торнадо. Я использовал AngularJS в качестве front end и торнадо python в качестве backend с сервером nginx. Я отправляю HTTP-запрос в Google+ API из AngularJS, а мой API-интерфейс Tornado перенаправляется на логин Google. После успешного входа в систему он перенаправляет обратно в мое приложение. Во время перенаправления я думаю, что он обновляется автоматически, т. Е. Есть два переадресации от Google.Tornado Google+ Oauth Код ошибки 400

Смотрите Есть два HTTP перенаправления вызова от смерча OAuth2

enter image description here

Это мой код:

class GoogleOAuth2LoginHandler(tornado.web.RequestHandler, tornado.auth.GoogleOAuth2Mixin): 
    @tornado.gen.coroutine 
     def get(self): 
      if self.get_argument('code', False): 
       user = yield self.get_authenticated_user(
        redirect_uri='http://your.site.com/auth/google', 
        code=self.get_argument('code') 
       ) 
       # Save the user with e.g. set_secure_cookie 
      else: 
       yield self.authorize_redirect(
        redirect_uri='http://your.site.com/auth/google', 
        client_id=self.settings['google_oauth']['key'], 
        scope=['profile', 'email'], 
        response_type='code', 
        extra_params={'approval_prompt': 'auto'} 

Ошибка:

Google auth error: HTTPResponse(_body=None,buffer=<_io.BytesIO object at 0xb37809bc>,code=400,effective_url=' https://accounts.google.com/o/oauth2/token ',error=HTTPError('HTTP 400: Bad Request',),headers={'X-Consumed-Content-Encoding': 'gzip', 'Alternate-Protocol': '443:quic,p=1', 'X-Xss-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Transfer-Encoding': 'chunked', 'Set-Cookie': 'NID=76=iaY_jJFPzvLg3_h3eqUFMt4fecbELKk9_bGJju-mwsHBNlxeDqSrtmpyazsrJ3mDgtDnTnzsw5_fjIfV8GcUAegoNgxGi5ynpcfg0vEWULSeVXKio_ANxEoK9C-F5oRs;Domain=.google.com;Path=/;Expires=Sat, 13-Aug-2016 10:17:46 GMT;HttpOnly', 'Expires': 'Fri, 12 Feb 2016 10:17:46 GMT', 'Server': 'GSE', 'Connection': 'close', 'Cache-Control': 'private, max-age=0', 'Date': 'Fri, 12 Feb 2016 10:17:46 GMT', 'P3p': 'CP="This is not a P3P policy! See https://support.google.com/accounts/answer/151657?hl=en for more info."', 'Alt-Svc': 'quic=":443"; ma=604800; v="30,29,28,27,26,25"', 'Content-Type': 'application/json; charset=utf-8', 'X-Frame-Options': 'SAMEORIGIN'},reason='Bad Request',request=,request_time=0.4158029556274414,time_info={})

+0

, пожалуйста, помогите мне .. –

ответ

0

У нас была такая же проблема с точно такой же конфигурацией (Tornado + nginx + angularjs). Я просто переписал часть аутентификации OAuth без торнадо, и проблема решена. Вы можете использовать asyncHttpClient tornado, но я использовал aiohttp, так как у меня был торнадо внутри асинчио. Ниже приведен новый код и прокомментированные части - это старый код.

from backend.helpers.async_oauth2.client import Client 

     oauth_client = Client(app_settings.security.google.client_id, app_settings.security.google.client_secret, 
           app_settings.security.google.redirect_uri, "https://accounts.google.com/o/oauth2/auth" 
           , "https://accounts.google.com/o/oauth2/token") 

     access = await oauth_client.get_token(code, grant_type="authorization_code") 

     # access = await self.get_authenticated_user(
     #  redirect_uri=app_settings.security.google.redirect_uri, 
     #  code=code) 

     # user = await self.oauth2_request(
     #  "https://www.googleapis.com/oauth2/v1/userinfo", 
     #  access_token=str(access["access_token"])) 

     user = await oauth_client.http_get(
      "https://www.googleapis.com/oauth2/v1/userinfo?{}".format(
       url_parse.urlencode({'access_token':str(access["access_token"])}))) 
Смежные вопросы