developer tip

사용자 개입없이 앱 (웹 또는 설치된 앱)을 승인하려면 어떻게합니까?

optionbox 2020. 12. 4. 08:07
반응형

사용자 개입없이 앱 (웹 또는 설치된 앱)을 승인하려면 어떻게합니까?


백그라운드 서비스에서 드라이브 파일에 액세스해야하는 웹 앱이 있다고 가정 해 보겠습니다. 액세스하는 파일을 소유하거나 소유자가 문서를 공유 한 Google 계정에서 실행됩니다.

내 앱에 새로 고침 토큰이 필요하다는 것을 이해하지만 한 번만 수행 할 것이기 때문에 이를 얻기 위해 코드를 작성하고 싶지 않습니다 .

NB. 이것은 서비스 계정을 사용하지 않습니다. 앱은 기존 Google 계정으로 실행됩니다. 서비스 계정은 일부 상황에서 유효한 접근 방식입니다. 그러나 Oauth Playground를 사용하여 앱을 시뮬레이션하는 기술은 많은 중복 작업을 절약 할 수 있으며 서비스 계정에 대한 공유가 지원되지 않는 모든 API에 적용됩니다.


https://developers.google.com/oauthplayground 에서 Oauth2 Playground를 사용하면됩니다.

단계 :-

  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 단계부터
  9. 1 단계를 클릭하고 Drive API https://www.googleapis.com/auth/drive를 선택합니다 (이 기술은 나열된 모든 Google API에서도 작동 함).
  10. API 승인을 클릭하십시오. Google 계정을 선택하고 액세스를 확인하라는 메시지가 표시됩니다.
  11. 2 단계 및 "토큰에 대한 인증 코드 교환"을 클릭합니다.
  12. 반환 된 새로 고침 토큰을 복사하여 앱, 소스 코드 또는 앱에서 검색 할 수있는 저장소 형식에 붙여 넣습니다.

이제 앱을 무인으로 실행할 수 있으며 https://developers.google.com/accounts/docs/OAuth2WebServer#offline설명 된대로 새로 고침 토큰 을 사용하여 액세스 토큰을 얻을 수 있습니다.

NB. 새로 고침 토큰은 Google에서 만료 될 수 있으므로 새 새로 고침 토큰을 받으려면 5 단계를 반복해야합니다. 이것의 증상은 새로 고침 토큰을 사용하려고 할 때 잘못된 부여가 반환되는 것입니다.

NB2. 당신이 당신의 자신의 (그리고 액세스 웹 응용 프로그램하려면이 기술은 잘 작동 에만 자신의) 드라이브 계정을 오직 한 번 실행된다 인증 코드를 작성하는 귀찮게하지 않고. 1 단계를 건너 뛰고 6 단계에서 "my.drive.app"을 자신의 이메일 주소로 바꿉니다. 새로 고침 토큰이 도난 당했을 때 보안 영향을 알고 있는지 확인하십시오.

이 Google 비디오 https://www.youtube.com/watch?v=hfWe1gPCnzc에 대한 링크는 아래 Woody의 의견을 참조 하십시오.

. . .

다음은 OAuth Playground에서 새로 고침 토큰을 사용하여 일부 드라이브 파일을 나열하는 방법을 보여주는 빠른 자바 스크립트 루틴입니다. 간단히 복사하여 Chrome 개발 콘솔에 붙여 넣거나 노드로 실행할 수 있습니다. 물론 자신의 자격 증명을 제공하십시오 (아래의 자격 증명은 모두 가짜입니다).

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

pinoyyid의 탁월한 답변에 대한 대체 경로를 추가하겠습니다 (나에게 작동하지 않았습니다-리디렉션 오류가 나타남).

OAuthPlayground를 사용하는 대신 HTTP REST API를 직접 사용할 수도 있습니다. 그래서 pinoyyid의 대답과 다른 점은 우리가 지역적으로 일을 할 것이라는 것입니다. pinoyyid의 답변에서 1-3 단계를 따르십시오. 나는 그들을 인용 할 것이다 :

  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를 만든 다음 선택에서 "웹 애플리케이션"을 선택).

이제 플레이 그라운드 대신 자격 증명에 다음을 추가합니다.

인증 된 자바 스크립트 소스 : http : // localhost (필요한지 모르겠지만 그냥하세요.)
인증 된 리디렉션 URI : http : // localhost : 8080

스크린 샷 (독일어) :

OAuth 소스 / 리디렉션 설정

아래의 파란색 버튼을 통해 변경 사항 실제로 저장 하십시오!

Now you'll probably want to use a GUI to build your HTTP requests. I used Insomnia but you can go with Postman or plain cURL. I recommend Insomnia for it allows you to go through the consent screens easily.

Build a new GET request with the following parameters:

URL: https://accounts.google.com/o/oauth2/v2/auth
Query Param: redirect_uri=http://localhost:8080
Query Param: prompt=consent
Query Param: response_type=code
Query Param: client_id=<your client id from OAuth credentials>
Query Param: scope=<your chosen scopes, e.g. https://www.googleapis.com/auth/drive.file>
Query Param: access_type=offline

If your tool of choice doesn't handle URL encoding automagically make sure to get it right yourself.

Before you fire your request set up a webserver to listen on http://localhost:8080. If you have node and npm installed run npm i express, then create an index.js:

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('ok');
  console.log(req)
});

app.listen(8080, function () {
  console.log('Listening on port 8080!');
});

And run the server via node index.js. I recommend to either not log the whole req object or to run node index.js | less for the full output will be huge.
There are very simple solutions for other languages, too. E.g. use PHP's built in web server on 8080 php -S localhost:8080.

Now fire your request (in Insomnia) and you should be prompted with the login:

로그인 프롬프트

Log in with your email and password and confirm the consent screen (should contain your chosen scopes).

Go back to your terminal and check the output. If you logged the whole thing scroll down (e.g. pgdown in less) until you see a line with code=4/....

Copy that code; it is your authorization code that you'll want to exchange for an access and refresh token. Don't copy too much - if there's an ampersand & do not copy it or anything after. & delimits query parameters. We just want the code.

Now set up a HTTP POST request pointing to https://www.googleapis.com/oauth2/v4/token as form URL encoded. In Insomnia you can just click that - in other tools you might have to set the header yourself to Content-Type: application/x-www-form-urlencoded.

Add the following parameters:

code=<the authorization code from the last step>
client_id=<your client ID again>
client_secret=<your client secret from the OAuth credentials>
redirect_uri=http://localhost:8080
grant_type=authorization_code

Again, make sure that the encoding is correct.

Fire your request and check the output from your server. In the response you should see a JSON object:

{
  "access_token": "xxxx",
  "expires_in": 3600,
  "refresh_token": "1/xxxx",
  "scope": "https://www.googleapis.com/auth/drive.file",
  "token_type": "Bearer"
}

access_token바로 사용할 수 있지만 유효 기간은 1 시간입니다. 새로 고침 토큰에 유의하십시오. 이것은 항상 * 새 액세스 토큰으로 교환 할 수있는 것입니다.

* 사용자가 비밀번호를 변경하거나 액세스를 취소하거나 6 개월 동안 비활성 상태 인 경우 절차를 반복해야합니다.

행복한 OAuthing !

참고 URL : https://stackoverflow.com/questions/19766912/how-do-i-authorise-an-app-web-or-installed-without-user-intervention

반응형