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

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

问题描述

假设我有一个需要在后台服务中访问云端硬盘文件的网络应用(mydriveapp").它将拥有它正在访问的文件,或者在所有者与其共享文档的 Google 帐户中运行.

Let's say that I have a web app ("mydriveapp") 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.

注意.这不是使用服务帐户.该应用程序将在传统的 Google 帐户下运行.在某些情况下,服务帐户是一种有效的方法.然而,使用 Oauth Playground 来模拟应用程序的技术可以节省大量多余的工作,并且适用于任何不支持共享到服务帐户的 API.

NB. This is NOT using a Service Account. The app will be run under a conventional Google account. 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.

推荐答案

这可以通过 https 的 Oauth2 Playground 完成://developers.google.com/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. 创建一组新凭据.Credentials/Create Credentials/OAuth Client Id 然后选择 Web application
  4. 包括 https://developers.google.com/oauthplayground 作为有效的重定向 URI
  5. 注意客户端 ID(网络应用)和客户端密钥
  6. 以 my.drive.app@gmail.com 的身份登录
  7. 前往 Oauth2 游乐场
  8. 在设置(齿轮图标)中,设置
    • OAuth 流程:服务器端
    • 访问类型:离线
    • 使用您自己的 OAuth 凭据:TICK
    • 客户端 ID 和客户端密钥:来自第 5 步
  1. Create the Google Account (eg. my.drive.app@gmail.com) - Or skip this step if you are using an existing account.
  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. Credentials/Create Credentials/OAuth Client Id then select Web application
  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-side
    • Access type: Offline
    • Use your own OAuth credentials: TICK
    • Client Id and Client Secret: from step 5

您的应用现在可以无人值守运行,并按照 https://中所述使用刷新令牌developer.google.com/accounts/docs/OAuth2WebServer#offline 以获取访问令牌.

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.

注意.请注意,刷新令牌可能会被 Google 过期,这意味着您需要重复步骤 5 以获取新的刷新令牌.这种情况的症状是当您尝试使用刷新令牌时返回 Invalid Grant.

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.如果您想要一个 Web 应用程序访问您自己的(并且您自己的)Drive 帐户,而无需编写只会运行一次的授权代码,则此技术非常有效.只需跳过第 1 步,并在第 6 步中将my.drive.app"替换为您自己的电子邮件地址.确保您了解刷新令牌被盗时的安全隐患.

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 6. make sure you are aware of the security implications if the Refresh Token gets stolen.

请参阅下面伍迪的评论,他链接到此 Google 视频 https://www.youtube.com/watch?v=hfWe1gPCnzc

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

...

这是一个快速的 JavaScript 例程,展示了如何使用 OAuth Playground 中的刷新令牌来列出一些云端硬盘文件.您可以简单地将其复制粘贴到 Chrome 开发控制台中,或使用 node.js 运行它.当然要提供你自己的凭据(以下都是假的).

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();

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

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