如何利用Google Calendar API和OAuth解决AJAX跨域限制问题

时间:2011-10-11 20:44:37

标签: jquery oauth google-calendar-api

在东部时间17:00编辑2011年12月12日以更正calendar_functions.js的XML代码中的两个拼写错误

我在笔记本电脑上本地工作,在动态IP背后,开发一个网站应用程序,通过AJAX与Google Calendar API进行交互。我不确定如何解决AJAX的跨域限制,因为谷歌的文档并没有真正谈到这一点。也许问题是,对Google的请求来自http://domain,而不是像http://domain.net这样的完整网址?

Google可以注册您的网络应用(http://code.google.com/apis/accounts/docs/RegistrationForWebAppsAuto.html),这会为我提供唯一的consumer_key / consumer_secret对,但注册表单不会接受http://domain作为域名。没有注册,该对是匿名/匿名的。

Stackoverflow帖子How does Google's javascript API get around the cross-domain security in AJAX解释说Google通过动态地将SCRIPT标签注入文档的头部来解决这个问题。我尝试了该线程中描述的三种方法,但在Chrome控制台中仍然有相同的消息:Access-Control-Allow-Origin不允许“来源http://domain。”

Google有关签署OAuth请求的文档位于http://code.google.com/apis/accounts/docs/OAuth_ref.html#SigningOAuth

这是我正在测试的表单,它会将一次事件添加到日历中:

<?php  // calendar.php

session_start();
require_once 'header.php';

?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Site's Title</title>

    <link rel="stylesheet" href="/styles.css">
    <script type="text/javascript" src="/js/jquery.js"></script>
    <script type="text/javascript" src="/js/UMDNJ.js"></script>
    <script type="text/javascript" src="/js/oauth_lib/sha1.js"></script>
    <script type="text/javascript" src="/js/oauth_lib/oauth.js"></script>
    <script type="text/javascript">
      $(document).ready( function() {
          $.getScript('/includes/calendar_functions.js', function() {
            alert("calendar_functions.js has been added");
          });
      });
    </script>
</head>
<body>

<h3>Add Calendar Event</h3>

<div id="addEvent">
<form action="calendar.php" id="addEventForm" method="POST">
  <label>Event title: </label><input type="text" name="eventTitle" id="eventTitle" size="20" /><br />
  <label>Event content: </label><textarea name="eventContent" id="eventContent" cols="20" rows="5"></textarea><br />
  <label>Location: </label><input type="text" name="eventLoc" id="eventLoc" size="20" /><br />
  <label>Start time: </label><input type="text" name="startTime" id="startTime" size="20" /><br />
  <label>End time: </label><input type="text" name="endTime" id="endTime" size="20" /><br />
  <input type="submit" name="eventSubmit" value="Submit" />
</form>
</div> <!-- /#addEvent -->

</body>
</html>


这里是jQuery处理表单的提交事件,借用this library中的借用代码:

// calendar_functions.js

dateObj = new Date();


function nonce( length ) {
  var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var result = "";
    for (var i = 0; i < length; ++i) {
    var rnum = Math.floor(Math.random() * chars.length);
    result += chars.substring(rnum, rnum+1);
    }
    return result;
}


  $("#addEventForm").submit(function() {

    // Make the XML for creating a new calendar event
    var eventTitle = $("#eventTitle").val();
    var eventContent = $("#eventContent").val();
    var startTime = $("#startTime").val();
    var endTime = $("#endTime").val();
    var eventLoc = $("#eventLoc").val();
    var eventXML = "<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gd='http://schemas.google.com/g/2005'>";
    eventXML += "<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event'></category>";
    eventXML += "<title type='text'>"+eventTitle+"</title>";
    eventXML += "<content type='text'>"+eventContent+"</content>";
    eventXML += "<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'></gd:transparency>";
    eventXML += "<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'></gd:eventStatus>";
    eventXML += "<gd:where valueString='"+eventLoc+"'></gd:where>";
    eventXML += "<gd:when startTime='"+startTime+"' endTime='"+endTime+"'></gd:when>";
    eventXML += "</entry>";


    // Set connection details
    var Connection = {
      method: "POST",
      url: "https://www.google.com/calendar/feeds/default/private/full",
      params: {
        oauth_version: "1.0",
        oauth_nonce: nonce(30),
        oauth_timestamp: dateObj.getTime(),
        oauth_consumer_key: "anonymous",
        oauth_token: "--hidden for stackoverflow post for security reasons--",
        oauth_signature_method: "HMAC-SHA1",
      }
    };

    var oauth_consumer_secret = "anonymous";
    var oauth_token_secret = "--hidden for stackoverflow post for security reasons--";
    var oauth_verifier = "--hidden for stackoverflow post for security reasons--";

    // Encode connection details
    var connectD = OAuth.percentEncode('oauth_version')+'="'+OAuth.percentEncode(Connection.params.oauth_version)+'"';
    connectD += ','+OAuth.percentEncode('oauth_nonce')+'="'+OAuth.percentEncode(Connection.params.oauth_nonce)+'"';
    connectD += ','+OAuth.percentEncode('oauth_timestamp')+'="'+OAuth.percentEncode(Connection.params.oauth_timestamp)+'"';
    connectD += ','+OAuth.percentEncode('oauth_consumer_key')+'="'+OAuth.percentEncode(Connection.params.oauth_consumer_key)+'"';
    connectD += ','+OAuth.percentEncode('oauth_token')+'="'+OAuth.percentEncode(Connection.params.oauth_token)+'"';
    connectD += ','+OAuth.percentEncode('oauth_signature_method')+'="'+OAuth.percentEncode(Connection.params.oauth_signature_method)+'"';

    // Make the base string
    var baseString = Connection.method+'&'+Connection.url+'&'+OAuth.SignatureMethod.normalizeParameters(Connection.params);    
    baseString = OAuth.percentEncode(baseString);

    // Make the signature
    var theKey = oauth_consumer_secret+'&'+oauth_token_secret;
    var b64pad = '=';    
    var signature = b64_hmac_sha1(theKey, baseString);

    // Add signature to encoded base connection details
    connectD += ','+OAuth.percentEncode('oauth_signature')+'="'+OAuth.percentEncode(signature)+'"';

//     alert(connectD);
//     alert(baseString);
    alert(signature);

    // Submit request to Google via AJAX
    $.ajax({
      type: 'POST',
      url: 'https://www.google.com/calendar/feeds/default/private/full',
      data: eventXML,
      dataType: 'xml',
      contentType: 'application/atom+xml',
//       headers: [
//          ['Access-Control-Allow-Origin', '*'],
//          ['Authorization', 'OAuth '+connectD]
//       ],
      beforeSend: function(xhr) {
        $("#addEvent").before('<div id="message_center">uploading...<br /></div>');
        xhr.setRequestHeader('Authorization', 'OAuth '+connectD);
      },
      success: function(data, textStatus, jqXHR) {
        $("#addEvent").before('<div id="message_center">Success!<br /> Data: '+data+'<br />textStatus: '+textStatus);
        console.log(data, textStatus);
      },
      error: function(jqXHR, textStatus, errorThrown) {
        $("#addEvent").before('<div id="message_center">'+textStatus+'<br />'+errorThrown+'</div>');
        var res = jqXHR.getAllResponseHeaders();
        console.info(jqXHR, textStatus, errorThrown);
      },
    }); 
    return false;
  });

我感谢任何人的建议。

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用的解决方法是将域添加到hosts文件并将其重定向到127.0.0.1 然后注册该域。

我不确定它是否会起作用,因为谷歌可能不得不与“服务器”进行通信 - 由于你是在防火墙之后他们不能这样做。