仅使用javascript刷新驱动器api的令牌

时间:2017-05-10 06:03:25

标签: javascript authentication google-drive-api google-oauth2

我的应用仅与JavaScript交互。我希望用户在首次验证后无需登录(脱机访问)即可访问其文件列表。我在堆栈或谷歌文档中尝试了许多解决方案。但无法获得任何解决方案。所以我上传了新的运行代码。但这是在用户每次没有在浏览器中登录gmail时要求用户登录。

我的HTML是:

<button id="authorize-button" style="display: none;">Authorize</button>
<pre id="content"></pre>

我的剧本:

 <script type="text/javascript">

  var CLIENT_ID = '****************';
  var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"];
  var SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly';
  var authorizeButton = document.getElementById('authorize-button');
  function handleClientLoad() {
    gapi.load('client:auth2', initClient);
  }
  function initClient() {
    gapi.client.init({
      discoveryDocs: DISCOVERY_DOCS,
      clientId: CLIENT_ID,
      scope: SCOPES
    }).then(function () {
      gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
      updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      authorizeButton.onclick = handleAuthClick;
    });
  }

  function updateSigninStatus(isSignedIn) {
    if (isSignedIn) {
      authorizeButton.style.display = 'none';
                listFiles();
    } else {
      authorizeButton.style.display = 'block';

    }
  }

  function handleAuthClick(event) {
    gapi.auth2.getAuthInstance().signIn();
  }

  function appendPre(message) {
    var pre = document.getElementById('content');
    var textContent = document.createTextNode(message + '\n');
    pre.appendChild(textContent);
  }

  function listFiles() {
    gapi.client.drive.files.list({
      'pageSize': 10,
      'fields': "nextPageToken, files(id, name)"
    }).then(function(response) {
      appendPre('Files:');
      var files = response.result.files;
      if (files && files.length > 0) {
        for (var i = 0; i < files.length; i++) {
          var file = files[i];
          appendPre(file.name + ' (' + file.id + ')');
        }
      } else {
        appendPre('No files found.');
      }
    });
  }

</script>
<script async defer src="https://apis.google.com/js/api.js"
  onload="this.onload=function(){};handleClientLoad()"
  onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

我也尝试过用户:

var auth2;
function init() {
alert('in init');
gapi.load('auth2', function() {
    auth2 = gapi.auth2.init({
        clientId: '**********************',
        scope: 'https://www.google.com/m8/feeds https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.appfolder'
    });
});
$('#authorize-button').click(function() {
    auth2.grantOfflineAccess({'redirect_uri' : 'postmessage', 'approval_prompt' : 'force'}).then(function(resp) {
    console.log(resp);
    var auth_code = resp.code;
});
});
}

在这里,我可以访问响应代码。但是如何使用它进行离线访问。请帮我一些代码。我也尝试了几乎所有文档并且非常困惑。

0 个答案:

没有答案