如何在没有用户干预的情况下授权应用程序(网页或已安装)? [英] How do I authorise an app (web or installed) without user intervention?

查看:276
本文介绍了如何在没有用户干预的情况下授权应用程序(网页或已安装)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个需要在后台服务中访问云端硬盘文件的网络应用程序。它将拥有它正在访问的文件,或者在拥有者共享文档的Google帐户中运行。



据我所知,我的应用程序需要刷新令牌,但我不想编写代码来获取,因为我只会永远只做一次。



注意。这不是使用服务帐户。该应用将在传统的Google帐户下运行。我不是说这是个好主意,在某些情况下,服务帐户是一种有效的方法。然而,使用Oauth Playground模拟应用程序的技术可以节省大量的重复劳动,并且适用于任何不支持与服务帐户共享的API。

解决方案

这可以通过 https://developers.google.com上的Oauth2 Playground完成/ oauthplayground



步骤:


  1. 创建Google帐户(例如my.drive.app@gmail.com)

  2. 使用API​​控制台注册mydriveapp( https://console.developers.google.com/apis/credentials/oauthclient?project=mydriveapp 或只是 https://console.developers.google.com/apis/

  3. 创建一组新的凭据(NB OAuth客户端ID )而不是 服务帐户密钥,然后从选择中选择Web应用程序) ://developers.google.com/oauthplaygroundrel =noreferrer> https://developers.google.com/oauthplayground 作为有效的重定向URI

  4. 请注意客户端ID(Web应用程序)和客户端密码

  5. 以my.drive.app@gmail.com登录

  6. 转到Oauth2游乐场

  7. 在设置(齿轮图标)中设置


    • Oauth流:服务器

    • 访问类型:离线

    • 使用您自己的OAuth凭据:TICK

    • 客户端ID和客户端密钥:来自步骤5
    • ul>
    • 点击第1步,然后选择Drive API https:// www .googleapis.com / auth / drive (话虽如此,这项技术也适用于任何列出的Google API)

    • 点击授权API。您将被提示选择您的Google帐户并确认访问权限。

    • 点击步骤2和兑换令牌的授权代码 复制返回的刷新令牌并将其粘贴到您的应用程序,源代码或应用程序可从中检索的某种形式的存储中。 您的应用程序可以现在无人值守运行,并按照 https://developers.google.com/所述使用刷新令牌accounts / docs / OAuth2WebServer#offline 以获得访问令牌。



      注意。请注意,刷新令牌可能会由Google过期,这意味着您需要重复步骤5以获取新的刷新令牌。当您尝试使用刷新令牌时,此症状将成为无效授予。



      NB2。如果您想要一个访问您自己的(仅限您自己的)云端硬盘帐户的Web应用程序,而无需编写只能运行一次的授权代码,该技术就可以很好地工作。只需跳过第1步,并在步骤5中用您自己的电子邮件地址替换my.drive.app。确保您知道刷新令牌被盗后的安全隐患。



      请参阅Woody的以下评论,他与此Google视频的链接 https://www.youtube。 com / watch?v = hfWe1gPCnzc







      以下是一个快速JavaScript例程,演示如何使用OAuth Playground中的Refresh Token列出一些Drive文件。您可以简单地将其复制粘贴到Chrome开发控制台中,或者使用节点运行它。

       函数get_access_token_using_saved_refresh_token(){
      //当然,提供您自己的凭证来自oauth playground
      const refresh_token =1 / 0PvMAoF9GaJFqbNsLZQg-f9NXEljQclmRP4Gwfdo_0;
      //从API控制台
      const client_id =559798723558-amtjh114mvtpiqis80lkl3kdo4gfm5k.apps.googleusercontent.com;
      //从API控制台
      const client_secret =WnGC6KJ91H40mg6H9r1eF9L;
      // https://developers.google.com/identity/protocols/OAuth2WebServer#offline
      const refresh_url =https://www.googleapis.com/oauth2/v4/token;
      $ b const post_body =`grant_type = refresh_token& client_id = $ {encodeURIComponent(client_id)}& client_secret = $ {encodeURIComponent(client_secret)}& refresh_token = $ {encodeURIComponent(refresh_token)}`;

      let refresh_request = {
      body:post_body,
      method:POST,
      headers:new Headers({
      'Content-Type': 'application / x-www-form-urlencoded'
      })
      }

      //发布到刷新端点,解析json响应并使用访问令牌调用文件.list
      fetch(refresh_url,refresh_request).then(response => {
      return(response.json());
      })。then(response_json => {
      console.log(response_json);
      files_list(response_json.access_token);
      });
      }

      //使用新获取的访问令牌列出一些Drive文件的快速和肮脏的函数
      函数files_list(access_token){
      const drive_url =https ://www.googleapis.com/drive/v3/files;
      let drive_request = {
      method:GET,
      headers:new Headers({
      Authorization:Bearer+ access_token
      })
      }
      fetch(drive_url,drive_request).then(response => {
      return(response.json());
      })。then(list => {
      console .log(找到一个名为+ list.files [0] .name)的文件;
      });
      }

      get_access_token_using_saved_refresh_token();


      Let's say that I have a web app that needs to access Drive files in a background service. It will either own the files it is accessing, or be run in a Google Account with which the owner has shared the documents.

      I understand that my app needs a refresh token, but I don't want to write the code to obtain that since I'll only ever do it once.

      NB. This is NOT using a Service Account. The app will be run under a conventional Google account. I'm not saying this is a good idea, Service Account is a valid approach in some situations. However the technique of using Oauth Playground to simulate the app can save a bunch of redundant effort, and applies to any APIs for which sharing to a Service Account is unsupported.

      解决方案

      This can be done with the Oauth2 Playground at https://developers.google.com/oauthplayground

      Steps:-

      1. Create the Google Account (eg. my.drive.app@gmail.com)
      2. Use the API console to register the mydriveapp (https://console.developers.google.com/apis/credentials/oauthclient?project=mydriveapp or just https://console.developers.google.com/apis/)
      3. Create a new set of credentials (NB OAuth Client ID not Service Account Key and then choose "Web Application" from the selection)
      4. Include https://developers.google.com/oauthplayground as a valid redirect URI
      5. Note the client ID (web app) and Client Secret
      6. Login as my.drive.app@gmail.com
      7. Go to Oauth2 playground
      8. In Settings (gear icon), set
        • Oauth flow: server
        • Access type: offline
        • Use your own OAuth credentials: TICK
        • Client Id and Client Secret: from step 5
      9. Click Step 1 and choose Drive API https://www.googleapis.com/auth/drive (having said that, this technique also works for any of the Google APIs listed)
      10. Click Authorize APIs. You will be prompted to choose your Google account and confirm access
      11. Click Step 2 and "Exchange Authorization code for tokens"
      12. Copy the returned Refresh Token and paste it into your app, source code or in to some form of storage from where your app can retrieve it.

      Your app can now run unattended, and use the Refresh Token as described https://developers.google.com/accounts/docs/OAuth2WebServer#offline to obtain an Access Token.

      NB. Be aware that the refresh token can be expired by Google which will mean that you need to repeat steps 5 onwards to get a new refresh token. The symptom of this will be a Invalid Grant returned when you try to use the refresh token.

      NB2. This technique works well if you want a web app which access your own (and only your own) Drive account, without bothering to write the authorization code which would only ever be run once. Just skip step 1, and replace "my.drive.app" with your own email address in step 5. make sure you are aware of the security implications if the Refresh Token gets stolen.

      See Woody's comment below where he links to this Google video https://www.youtube.com/watch?v=hfWe1gPCnzc

      . . .

      Here is a quick JavaScript routine that shows how to use the Refresh Token from the OAuth Playground to list some Drive files. You can simply copy-paste it into Chrome dev console, or run it with node. Of course provide your own credentials (the ones below are all fake).

      function get_access_token_using_saved_refresh_token() {
          // from the oauth playground
          const refresh_token = "1/0PvMAoF9GaJFqbNsLZQg-f9NXEljQclmRP4Gwfdo_0";
          // from the API console
          const client_id = "559798723558-amtjh114mvtpiqis80lkl3kdo4gfm5k.apps.googleusercontent.com";
          // from the API console
          const client_secret = "WnGC6KJ91H40mg6H9r1eF9L";
          // from https://developers.google.com/identity/protocols/OAuth2WebServer#offline
          const refresh_url = "https://www.googleapis.com/oauth2/v4/token";
      
          const post_body = `grant_type=refresh_token&client_id=${encodeURIComponent(client_id)}&client_secret=${encodeURIComponent(client_secret)}&refresh_token=${encodeURIComponent(refresh_token)}`;
      
          let refresh_request = {
              body: post_body,
              method: "POST",
              headers: new Headers({
                  'Content-Type': 'application/x-www-form-urlencoded'
              })
          }
      
          // post to the refresh endpoint, parse the json response and use the access token to call files.list
          fetch(refresh_url, refresh_request).then( response => {
                  return(response.json());
              }).then( response_json =>  {
                  console.log(response_json);
                  files_list(response_json.access_token);
          });
      }
      
      // a quick and dirty function to list some Drive files using the newly acquired access token
      function files_list (access_token) {
          const drive_url = "https://www.googleapis.com/drive/v3/files";
          let drive_request = {
              method: "GET",
              headers: new Headers({
                  Authorization: "Bearer "+access_token
              })
          }
          fetch(drive_url, drive_request).then( response => {
              return(response.json());
          }).then( list =>  {
              console.log("Found a file called "+list.files[0].name);
          });
      }
      
      get_access_token_using_saved_refresh_token();
      

      这篇关于如何在没有用户干预的情况下授权应用程序(网页或已安装)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆