Google ID 서비스 또는 OAuth 2.0 승인 코드 흐름을 사용하는 경우 Google은 리디렉션 엔드포인트에 POST 메서드를 사용하여 ID 토큰을 반환합니다. 또는 OIDC 암시적 흐름은 GET 요청을 사용합니다. 따라서 애플리케이션은 수신된 사용자 인증 정보를 서버에 안전하게 전송해야 합니다.
이는 암시적 흐름으로, ID 토큰이 URL 프래그먼트 내에 반환되며 클라이언트 측 JavaScript가 이를 파싱해야 합니다. 애플리케이션은 요청의 진위성을 보장하고 CSRF와 같은 공격을 방지하기 위해 자체 유효성 검사 메커니즘을 구현해야 합니다.
HTTP/1.1 302 Found Location: https://<REDIRECT_URI>#access_token=<ACCESS_TOKEN>&token_type=bearer&expires_in=<TIME_IN_SECONDS>&scope=<SCOPE>&state=<STATE_STRING>
ID 토큰은 credential 필드로 다시 전송됩니다. 서버에 ID 토큰을 전송할 준비를 할 때 GIS 라이브러리는 g_csrf_token를 헤더 쿠키와 요청 본문에 자동으로 추가합니다. 다음은 POST 요청의 예입니다.
POST /auth/token-verification HTTP/1.1 Host: example.com Content-Type: application/json;charset=UTF-8 Cookie: g_csrf_token=<CSRF_TOKEN> Origin: https://example.com Content-Length: <LENGTH_OF_JSON_BODY> { "credential": "<ID_TOKEN>", "g_csrf_token": "<CSRF_TOKEN>", "client_id": "<CLIENT_ID>" }
크로스 사이트 요청 위조 (CSRF) 공격을 방지하기 위해
g_csrf_token유효성 검사:g_csrf_token쿠키에서 CSRF 토큰 값을 추출합니다.- 요청 본문에서 CSRF 토큰 값을 추출합니다. GIS 라이브러리는 이 토큰을 POST 요청 본문에
g_csrf_token라는 매개변수로 포함합니다. - 두 토큰 값을 비교합니다.
- 두 값이 모두 있고 완전히 일치하면 요청이 적법한 것으로 간주되며 도메인에서 시작된 것으로 간주됩니다.
- 값이 없거나 일치하지 않으면 서버에서 요청을 거부해야 합니다.
이 확인은 자체 도메인에서 실행되는 JavaScript에서 요청이 시작되었는지 확인합니다. 자체 도메인만
g_csrf_token쿠키에 액세스할 수 있기 때문입니다.
ID 토큰을 확인합니다.
To verify that the token is valid, ensure that the following criteria are satisfied:
- The ID token is properly signed by Google. Use Google's public keys
(available in
JWK or
PEM format)
to verify the token's signature. These keys are regularly rotated; examine
the
Cache-Controlheader in the response to determine when you should retrieve them again. - The value of
audin the ID token is equal to one of your app's client IDs. This check is necessary to prevent ID tokens issued to a malicious app being used to access data about the same user on your app's backend server. - The value of
issin the ID token is equal toaccounts.google.comorhttps://accounts.google.com. - The expiry time (
exp) of the ID token has not passed. - If you need to validate that the ID token represents a Google Workspace or Cloud
organization account, you can check the
hdclaim, which indicates the hosted domain of the user. This must be used when restricting access to a resource to only members of certain domains. The absence of this claim indicates that the account does not belong to a Google hosted domain.
Using the
email,email_verifiedandhdfields, you can determine if Google hosts and is authoritative for an email address. In the cases where Google is authoritative, the user is known to be the legitimate account owner, and you may skip password or other challenge methods.Cases where Google is authoritative:
emailhas a@gmail.comsuffix, this is a Gmail account.email_verifiedis true andhdis set, this is a Google Workspace account.
Users may register for Google Accounts without using Gmail or Google Workspace. When
emaildoes not contain a@gmail.comsuffix andhdis absent, Google is not authoritative and password or other challenge methods are recommended to verify the user.email_verifiedcan also be true as Google initially verified the user when the Google account was created, however ownership of the third party email account may have since changed.Rather than writing your own code to perform these verification steps, we strongly recommend using a Google API client library for your platform, or a general-purpose JWT library. For development and debugging, you can call our
tokeninfovalidation endpoint.Google API 클라이언트 라이브러리 사용
Google API 클라이언트 라이브러리 중 하나 (예: 자바, Node.js PHP Python) 프로덕션 환경에서 Google ID 토큰의 유효성을 검사하는 데 권장되는 방법입니다.
<ph type="x-smartling-placeholder"></ph> <ph type="x-smartling-placeholder"> </ph> 를 통해 개인정보처리방침을 정의할 수 있습니다. <ph type="x-smartling-placeholder">자바 Java에서 ID 토큰의 유효성을 검사하려면 GoogleIdTokenVerifier 객체에 대한 호출을 확인할 수 있습니다. 예를 들면 다음과 같습니다.
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload; import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; ... GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory) // Specify the WEB_CLIENT_ID of the app that accesses the backend: .setAudience(Collections.singletonList(WEB_CLIENT_ID)) // Or, if multiple clients access the backend: //.setAudience(Arrays.asList(WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3)) .build(); // (Receive idTokenString by HTTPS POST) GoogleIdToken idToken = verifier.verify(idTokenString); if (idToken != null) { Payload payload = idToken.getPayload(); // Print user identifier. This ID is unique to each Google Account, making it suitable for // use as a primary key during account lookup. Email is not a good choice because it can be // changed by the user. String userId = payload.getSubject(); System.out.println("User ID: " + userId); // Get profile information from payload String email = payload.getEmail(); boolean emailVerified = Boolean.valueOf(payload.getEmailVerified()); String name = (String) payload.get("name"); String pictureUrl = (String) payload.get("picture"); String locale = (String) payload.get("locale"); String familyName = (String) payload.get("family_name"); String givenName = (String) payload.get("given_name"); // Use or store profile information // ... } else { System.out.println("Invalid ID token."); }
GoogleIdTokenVerifier.verify()메서드가 JWT를 확인합니다. 서명,aud클레임,iss클레임 및exp소유권 주장.ID 토큰이 Google Workspace 또는 Cloud를 나타내는지 확인해야 하는 경우 조직 계정의 경우 도메인 이름을 확인하여
hd소유권 주장을 확인할 수 있습니다.Payload.getHostedDomain()메서드에서 반환됩니다. 소유권 주장email건이 계정을 도메인에서 관리하기에 충분하지 않습니다. 또는 조직이나 그 안에서 활용할 수 있습니다.</ph> 를 통해 개인정보처리방침을 정의할 수 있습니다. <ph type="x-smartling-placeholder">Node.js Node.js에서 ID 토큰을 검증하려면 Node.js용 Google 인증 라이브러리를 사용하세요. 라이브러리를 설치합니다.
드림 그런 다음npm install google-auth-library --save
verifyIdToken()함수를 호출합니다. 예를 들면 다음과 같습니다.const {OAuth2Client} = require('google-auth-library'); const client = new OAuth2Client(); async function verify() { const ticket = await client.verifyIdToken({ idToken: token, audience: WEB_CLIENT_ID, // Specify the WEB_CLIENT_ID of the app that accesses the backend // Or, if multiple clients access the backend: //[WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3] }); const payload = ticket.getPayload(); // This ID is unique to each Google Account, making it suitable for use as a primary key // during account lookup. Email is not a good choice because it can be changed by the user. const userid = payload['sub']; // If the request specified a Google Workspace domain: // const domain = payload['hd']; } verify().catch(console.error);
verifyIdToken함수는 JWT 서명,aud클레임,exp클레임 및iss클레임.ID 토큰이 Google Workspace 또는 Cloud를 나타내는지 확인해야 하는 경우 조직 계정에 대한
hd클레임을 확인하면 사용자 도메인입니다. 리소스에 대한 액세스 권한을 구성원으로만 제한할 때 사용해야 합니다. 특정 도메인의 사용자를 관리할 수 있습니다 이 소유권 주장이 없으면 계정이 다음 항목에 속하지 않음을 나타냅니다. Google에서 호스팅하는 도메인일 수 있습니다</ph> 를 통해 개인정보처리방침을 정의할 수 있습니다. <ph type="x-smartling-placeholder">PHP PHP에서 ID 토큰의 유효성을 검사하려면 PHP용 Google API 클라이언트 라이브러리를 사용합니다. 라이브러리를 설치합니다 (예: Composer 사용).
드림 그런 다음composer require google/apiclient
verifyIdToken()함수를 호출합니다. 예를 들면 다음과 같습니다.require_once 'vendor/autoload.php'; // Get $id_token via HTTPS POST. $client = new Google_Client(['client_id' => $WEB_CLIENT_ID]); // Specify the WEB_CLIENT_ID of the app that accesses the backend $payload = $client->verifyIdToken($id_token); if ($payload) { // This ID is unique to each Google Account, making it suitable for use as a primary key // during account lookup. Email is not a good choice because it can be changed by the user. $userid = $payload['sub']; // If the request specified a Google Workspace domain //$domain = $payload['hd']; } else { // Invalid ID token }
verifyIdToken함수는 JWT 서명,aud클레임,exp클레임 및iss클레임.ID 토큰이 Google Workspace 또는 Cloud를 나타내는지 확인해야 하는 경우 조직 계정에 대한
hd클레임을 확인하면 사용자 도메인입니다. 리소스에 대한 액세스 권한을 구성원으로만 제한할 때 사용해야 합니다. 특정 도메인의 사용자를 관리할 수 있습니다 이 소유권 주장이 없으면 계정이 다음 항목에 속하지 않음을 나타냅니다. Google에서 호스팅하는 도메인일 수 있습니다</ph> Python Python에서 ID 토큰의 유효성을 검사하려면 verify_oauth2_token 함수를 사용하세요. 예를 들면 다음과 같습니다.
from google.oauth2 import id_token from google.auth.transport import requests # (Receive token by HTTPS POST) # ... try: # Specify the WEB_CLIENT_ID of the app that accesses the backend: idinfo = id_token.verify_oauth2_token(token, requests.Request(), WEB_CLIENT_ID) # Or, if multiple clients access the backend server: # idinfo = id_token.verify_oauth2_token(token, requests.Request()) # if idinfo['aud'] not in [WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3]: # raise ValueError('Could not verify audience.') # If the request specified a Google Workspace domain # if idinfo['hd'] != DOMAIN_NAME: # raise ValueError('Wrong domain name.') # ID token is valid. Get the user's Google Account ID from the decoded token. # This ID is unique to each Google Account, making it suitable for use as a primary key # during account lookup. Email is not a good choice because it can be changed by the user. userid = idinfo['sub'] except ValueError: # Invalid token pass
verify_oauth2_token함수가 JWT 확인 서명,aud클레임,exp클레임hd도 확인해야 합니다. 배상 청구 (해당되는 경우)를verify_oauth2_token가 반환됩니다. 여러 클라이언트가 백엔드 서버에서aud클레임을 수동으로 확인합니다.- The ID token is properly signed by Google. Use Google's public keys
(available in
JWK or
PEM format)
to verify the token's signature. These keys are regularly rotated; examine
the
토큰의 유효성이 확인되면 Google ID 토큰의 정보를 사용하여 사이트의 계정 상태를 상호 연관시킬 수 있습니다.
등록되지 않은 사용자: 필요한 경우 사용자가 추가 프로필 정보를 제공할 수 있는 가입 사용자 인터페이스(UI)를 표시할 수 있습니다. 또한 사용자가 자동으로 새 계정과 로그인된 사용자 세션을 만들 수 있습니다.
사이트에 이미 있는 기존 계정: 최종 사용자가 비밀번호를 입력하고 기존 계정을 Google 사용자 인증 정보와 연결할 수 있는 웹페이지를 표시할 수 있습니다. 이렇게 하면 사용자가 기존 계정에 액세스할 수 있음을 확인할 수 있습니다.
재방문하는 제휴 사용자: 사용자를 자동으로 로그인할 수 있습니다.