program tip

Google 인증 API 액세스 토큰을 확인하려면 어떻게합니까?

radiobox 2020. 8. 4. 07:38
반응형

Google 인증 API 액세스 토큰을 확인하려면 어떻게합니까?


Google 인증 액세스 토큰을 확인하려면 어떻게합니까?

어떻게 든 Google에 쿼리하고 다음을 묻습니다. [given access token]은 [example@example.com] Google 계정에 유효합니까?

간단한 버전 : 웹 애플리케이션 용 Google 인증 API :: OAuth 인증을
통해 제공된 액세스 토큰을 사용하여 다양한 Google 서비스에서 데이터를 요청 하는 방법이 분명합니다 . 주어진 액세스 토큰이 주어진 Google 계정에 유효한지 확인하는 방법은 명확하지 않습니다. 방법을 알고 싶습니다.

Long version :
토큰 기반 인증을 사용하는 API를 개발 중입니다. 유효한 사용자 이름 + 암호를 제공하거나 N 개의 검증 가능한 서비스 중 하나에서 타사 토큰을 제공하면 토큰이 반환됩니다 .

타사 서비스 중 하나는 Google이므로 사용자는 Google 계정을 사용하여 내 서비스에 대해 인증 할 수 있습니다. 나중에 Yahoo 계정, 신뢰할 수있는 OpenID 제공 업체 등을 포함하도록 확장 될 것입니다.

Google 기반 액세스의 개략도 :

대체 텍스트 http://webignition.net/images/figures/auth_figure002.png

'API'엔터티는 내 모든 권한을 갖습니다. '공개 인터페이스'엔터티는 모든 웹 또는 데스크톱 기반 앱입니다. 일부 공용 인터페이스는 내 통제하에 있고, 다른 공용 인터페이스는 그렇지 않으며 다른 인터페이스는 여전히 알지 못할 수도 있습니다.

따라서 3 단계에서 API에 제공 한 토큰을 신뢰할 수 없습니다. 해당 Google 계정 이메일 주소와 함께 제공됩니다.

어떻게 든 Google에 쿼리하고 질문해야합니다 : 이 액세스 토큰은 example@example.com에 유효 합니까?

이 경우 example@example.com은 Google 계정 고유 식별자입니다. 누군가 Google 계정에 로그인 할 때 사용하는 이메일 주소입니다. 이것은 Gmail 주소로 가정 할 수 없습니다. 누군가 Gmail 계정이 없어도 Google 계정을 보유 할 수 있습니다.

Google 문서에는 액세스 토큰을 사용하여 여러 Google 서비스에서 데이터를 검색하는 방법이 명시되어 있습니다. 주어진 액세스 토큰이 처음에 유효한지 확인할 수있는 방법은 없습니다.

업데이트 토큰은 N Google 서비스에 유효합니다. 특정 사용자가 실제로 사용하는 모든 Google 서비스의 하위 집합을 알지 못하기 때문에이를 확인하기 위해 Google 서비스에 대해 토큰을 시도 할 수 없습니다.

또한 Google 인증 액세스 토큰을 사용하여 Google 서비스에 액세스하는 것은 결코 아닙니다. 단지 Google 사용자가 실제로 누구인지 확인하는 수단 일뿐입니다. 다른 방법이 있다면 기꺼이 시도해보십시오.


사용자 확인을 위해 accessToken으로 액세스 토큰을 게시하고 게시하고 응답을 얻으십시오.

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=accessToken

브라우저에서도 주소 표시 줄을 시도하고 httppost 및 java의 응답을 사용할 수도 있습니다.

응답은

{
     "issued_to": "xxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
     "audience": "xxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
     "user_id": "xxxxxxxxxxxxxxxxxxxxxxx",
     "scope": "https://www.googleapis.com/auth/userinfo.profile https://gdata.youtube.com",
     "expires_in": 3340,
     "access_type": "offline"
    }

범위는 accessToken의 주어진 권한입니다. 이 링크 에서 범위 ID를 확인할 수 있습니다


이 엔드 포인트를 사용하여 Google 인증 액세스 토큰을 확인할 수 있습니다.

https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=<access_token>

이것은 Google V3 OAuth AccessToken 유효성 검사 엔드 포인트입니다. 아래 Google 문서에서 확인할 수 있습니다. ( OAUTH 2.0 ENDPOINTS탭에서)

https://developers.google.com/identity/protocols/OAuth2UserAgent#validate-access-token


function authenticate_google_OAuthtoken($user_id)
{
    $access_token   = google_get_user_token($user_id); // get existing token from DB
    $redirecturl    = $Google_Permissions->redirecturl;
    $client_id      = $Google_Permissions->client_id;
    $client_secret  = $Google_Permissions->client_secret;
    $redirect_uri   = $Google_Permissions->redirect_uri;
    $max_results    = $Google_Permissions->max_results;

    $url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='.$access_token;
    $response_contacts  =  curl_get_responce_contents($url);
    $response   =   (json_decode($response_contacts));

    if(isset($response->issued_to))
    {
        return true;
    }
    else if(isset($response->error))
    {
        return false;
    }
}

대부분의 답변은 유효하지만 옳지 않습니다. JWT의 아이디어는 매번 발행자에게 연락 할 필요없이 토큰의 유효성을 검사 할 수 있다는 것입니다. 토큰을 서명하는 데 사용 된 인증서 google의 알려진 공개 키로 ID를 확인하고 토큰의 서명을 확인해야합니다.

그 이유와 방법은 다음 게시물을 참조하십시오.

http://ncona.com/2015/02/ consumer-a-google-id-token-from-a-server /


Google oauth 코드 흐름 응답 외에도 암호화 된 형식의 유효성 검사 정보에 ​​유용한 access_token반환 값 id_token도 있습니다.

One thing that makes ID tokens useful is that fact that you can pass them around different components of your app. These components can use an ID token as a lightweight authentication mechanism authenticating the app and the user. But before you can use the information in the ID token or rely on it as an assertion that the user has authenticated, you must validate it.

Validation of an ID token requires several steps:

  • Verify that the ID token is a JWT which is properly signed with an appropriate Google public key.
  • Verify that the value of aud in the ID token is equal to your app’s client ID.
  • Verify that the value of iss in the ID token is equal to accounts.google.com or https://accounts.google.com.
  • Verify that the expiry time (exp) of the ID token has not passed.
  • If you passed a hd parameter in the request, verify that the ID token has a hd claim that matches your Google Apps hosted domain.

https://developers.google.com/identity/protocols/OpenIDConnect#validatinganidtoken link has code samples for validation of ID tokens.

See also https://security.stackexchange.com/questions/37818/why-use-openid-connect-instead-of-plain-oauth.


I need to somehow query Google and ask: Is this access token valid for example@example.com?

No. All you need is request standard login with Federated Login for Google Account Users from your API domain. And only after that you could compare "persistent user ID" with one you have from 'public interface'.

The value of realm is used on the Google Federated Login page to identify the requesting site to the user. It is also used to determine the value of the persistent user ID returned by Google.

So you need be from same domain as 'public interface'.

And do not forget that user needs to be sure that your API could be trusted ;) So Google will ask user if it allows you to check for his identity.


Try making an OAuth-authenticated request using your token to https://www.google.com/accounts/AuthSubTokenInfo. This is only documented to work for AuthSub, but it works for OAuth too. It won't tell you which user the token is for, but it will tell you which services it's valid for, and the request will fail if the token is invalid or has been revoked.


An arbitrary OAuth access token can't be used for authentication, because the meaning of the token is outside of the OAuth Core spec. It could be intended for a single use or narrow expiration window, or it could provide access which the user doesn't want to give. It's also opaque, and the OAuth consumer which obtained it might never have seen any type of user identifier.

An OAuth service provider and one or more consumers could easily use OAuth to provide a verifiable authentication token, and there are proposals and ideas to do this out there, but an arbitrary service provider speaking only OAuth Core can't provide this without other co-ordination with a consumer. The Google-specific AuthSubTokenInfo REST method, along with the user's identifier, is close, but it isn't suitable, either, since it could invalidate the token, or the token could be expired.

If your Google ID is an OpenId identifier, and your 'public interface' is either a web app or can call up the user's browser, then you should probably use Google's OpenID OP.

OpenID consists of just sending the user to the OP and getting a signed assertion back. The interaction is solely for the benefit of the RP. There is no long-lived token or other user-specific handle which could be used to indicate that a RP has successfully authenticated a user with an OP.

One way to verify a previous authentication against an OpenID identifier is to just perform authentication again, assuming the same user-agent is being used. The OP should be able to return a positive assertion without user interaction (by verifying a cookie or client cert, for example). The OP is free to require another user interaction, and probably will if the authentication request is coming from another domain (my OP gives me the option to re-authenticate this particular RP without interacting in the future). And in Google's case, the UI that the user went through to get the OAuth token might not use the same session identifier, so the user will have to re-authenticate. But in any case, you'll be able to assert the identity.


Here's an example using Guzzle:

/**
 * @param string $accessToken JSON-encoded access token as returned by \Google_Client->getAccessToken() or raw access token
 * @return array|false False if token is invalid or array in the form
 * 
 * array (
 *   'issued_to' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
 *   'audience' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
 *   'scope' => 'https://www.googleapis.com/auth/calendar',
 *   'expires_in' => 3350,
 *   'access_type' => 'offline',
 * )
 */
public static function tokenInfo($accessToken) {
    if(!strlen($accessToken)) {
        return false;
    }

    if($accessToken[0] === '{') {
        $accessToken = json_decode($accessToken)->access_token;
    }

    $guzzle = new \GuzzleHttp\Client();

    try {
        $resp = $guzzle->get('https://www.googleapis.com/oauth2/v1/tokeninfo', [
            'query' => ['access_token' => $accessToken],
        ]);
    } catch(ClientException $ex) {
        return false;
    }

    return $resp->json();
}

Google could never answer your question, because it's not "is this access token valid?" It's token+secret.

참고URL : https://stackoverflow.com/questions/359472/how-can-i-verify-a-google-authentication-api-access-token

반응형