2015-06-01 2 views
1

Я пытаюсь подключиться к google oauth. Я использовал JavaScript, чтобы установить соединение с Google и получить код, я тогда понимаю, что нужно поменять этот код на лексемы, как описано здесь: https://developers.google.com/identity/protocols/OAuth2WebServerGoogle api oauth prolog

код у меня есть это:

:- use_module(library(http/http_dispatch)). 
:- use_module(library(http/http_error)). 
:- use_module(library(http/html_write)). 
:- use_module(library(http/http_session)). 
:- use_module(library(http/js_write)). 
:- use_module(library(http/http_files)). 
:- use_module(library(http/json)). 
:- use_module(library(http/http_open)). 
:- use_module(library(http/http_json)). 
:- use_module(library(http/http_parameters)). 
:- use_module(library(http/http_client)). 
:- use_module(library(http/http_ssl_plugin)). 

post_to_google(Reply,Code,Client_Id,Client_Secret):- 
     Grant_type=authorization_code, 
     http_post(
     'http://requestb.in/10qo0si1', 
     %'https://www.googleapis.com/oauth2/v3/token', 
     form([ 
      code=Code, 
      client_id=Client_Id, 
      client_secret=Client_Secret, 
      redirect_uri='http://localhost:5000/', 
      grant_type=Grant_type 
     ]), 
     Reply, 
     [] 
    ). 

Если Я запрашиваю post_to_google(R,123,id,secret). Это отправляет запрос на запрос bin, поэтому я могу его проверить (http://requestb.in/10qo0si1?inspect), и я получаю ответ «ok».

Если я прокомментирую бланк запроса и заменим адрес google, я получаю false. Где бы ожидать что-то вроде { "error": "invalid_request" } или если запрашивается с чем-то правильные учетные данные, как:

{ 
    "access_token":"1/fFAGRNJru1FTz70BzhT3Zg", 
    "expires_in":3920, 
    "token_type":"Bearer" 
} 

Должен ли я сделать что-то другое, потому что это протокол HTTPS или я делаю ошибку где-то еще? Трассировка, похоже, не сбой в address/4 за несоответствие протокола?

ответ

0

ОК, наконец, отработал этот шаг. Если кому-то интересно:

Использование status_code (_ErrorCode), казалось, разрешило проблему с streampair, и мне нужно было установить redirect_uri = 'postmessage' для запроса на работу. Я также использовал http_open, а не http_post.

:- use_module(library(http/thread_httpd)). 
:- use_module(library(http/http_dispatch)). 
:- use_module(library(http/http_error)). 
:- use_module(library(http/html_write)). 
:- use_module(library(http/http_session)). 
:- use_module(library(http/js_write)). 
:- use_module(library(http/http_files)). 
:- use_module(library(http/json)). 
:- use_module(library(http/http_open)). 
:- use_module(library(http/http_json)). 
:- use_module(library(http/http_parameters)). 
:- use_module(library(http/http_client)). 
:- use_module(library(http/http_ssl_plugin)). 

:- use_module('../prolog/google_client'). 

http:location(files, '/f', []). 

:- http_handler('/', home_page, []). 
:- http_handler('/gconnect', gconnect, []). 

:- http_handler(files(.), http_reply_from_files('test_files', []), [prefix]). 

:- dynamic 
    my_code/1. 
server :- 
    server(5000). 

server(Port) :- 
     http_server(http_dispatch, [port(Port)]), 
    format("Server should be on port 5000 to work with google settings- is it?"). 

read_client_secrets(MyWeb,Client_Id,Client_Secret) :- 
    open('client_secrets.json',read,Stream), 
    json_read_dict(Stream,Dict), 
    _{web:MyWeb} :< Dict, 
    _{ 
     auth_provider_x509_cert_url:Auth_url, 
     auth_uri:Auth_uri, 
     client_email:Client_email, 
     client_id:Client_Id, 
     client_secret:Client_Secret, 
     client_x509_cert_url:Client_cert_url, 
     javascript_origins:Javascript_origins, 
     redirect_uris: Redirect_uris, 
     token_uri:Token_Uri 
    } :<MyWeb, 
    close(Stream). 



post_to_google(Profile,Code,CID,CS):- 

    ListofData=[ 
       code=Code, 
       client_id=CID, 
       client_secret=CS, 
       redirect_uri='postmessage', 
       grant_type=authorization_code 

       ], 
     http_open('https://www.googleapis.com/oauth2/v3/token', In, 
        [ status_code(_ErrorCode), 
      method(post),post(form(ListofData)) 
        ]), 
    call_cleanup(json_read_dict(In, Profile), 
      close(In)). 


home_page(Request) :- 
    reply_html_page(
     [title('Oauth Test'), 
     script([type='text/javascript', 
      src='//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js'],[]), 
     script([type='text/javascript', 
      src='//apis.google.com/js/platform.js?onload=start'],[]), 
     \call_back_script 
     ], 
     [h1('hello'), 
     p('test'), 
     \google_loginButton 
     ]). 

gconnect(Request):- 
    %I need to get the code from the request 
    http_parameters(Request,[code(Code,[default(default)])]), 
    read_client_secrets(_MyWeb,Client_Id,Client_Secret), 
    post_to_google(Reply,Code,Client_Id,Client_Secret), 
    reply_json(Reply). 


call_back_script --> 
    js_script({|javascript|| 
       console.log("script runs"); 
       function signInCallback(authResult) { 
         console.log("got to call back"); 
         if (authResult['code']) { 
         console.log("has code"); 
         console.log(authResult['code']); 
      $('#signInButton').attr('style','display: none'); 

      $.post("/gconnect", 
       {code:authResult['code']}, 
       function(data,status){ 
       //console.log("Data: " + data.reply + "\nStatus: " + status); 
       console.log("Access Token: " + data.access_token + "\nExpires in : " + data.expires_in + "\nToken_type : " + data.token_type + "\nStatus: " + status); 
       }); 
      /* 
      $.ajax({ 
        type: 'POST', 
        url: '/gconnect', 
        processData:false, 
        //contentType: 'application/x-www-form-urlencoded; charset=UTF-8', 
        contentType: 'application/octet-stream; charset=utf-8', 
        data: {code:authResult['code']}, 
        success: function(result){ 
         console.log("success"); 
         console.log(result); 
        } 
       }); 
          */ 

      } 
       } 

       |}). 


google_loginButton --> 
    html([div([id="signInButton"],[ 
      span([ 
      class="g-signin", 
      data-scope="openid email", 
      data-clientid="124024716168-p5lvtlj5jinp9u912s3f7v3a5cuvj2g8.apps.googleusercontent.com", 
      data-redirecturi="postmessage", 
      data-accesstype="offline", 
      data-cookiepolicy="single_host_origin", 
      data-callback="signInCallback", 
      data-approvalprompt="force"],[]) 
      ])]).