Google ile Oturum Açma özelliğini, arka uç sunucusuyla iletişim kuran bir uygulama veya siteyle kullanıyorsanız sunucuda o anda oturum açmış olan kullanıcıyı belirlemeniz gerekebilir. Bunu güvenli bir şekilde yapmak için, kullanıcı başarıyla oturum açtıktan sonra kullanıcının kimlik jetonunu HTTPS kullanarak sunucunuza gönderin. Ardından, sunucuda kimlik jetonunun bütünlüğünü doğrulayın ve oturum oluşturmak veya yeni bir hesap oluşturmak için jetonda yer alan kullanıcı bilgilerini kullanın.
Kimlik jetonunu sunucunuza gönderin
Öncelikle, kullanıcı oturum açtığında kullanıcının kimlik jetonunu alın:
-
Google ile Oturum Açma'yı yapılandırdığınızda
requestIdToken
yöntemini çağırın ve sunucunuzun web istemcisi kimliğini iletin.// Request only the user's ID token, which can be used to identify the // user securely to your backend. This will contain the user's basic // profile (name, profile picture URL, etc) so you should not need to // make an additional call to personalize your application. GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.server_client_id)) .requestEmail() .build();
-
Uygulamanız başladığında kullanıcının
silentSignIn
numarasını arayarak bu cihazda veya başka bir cihazda Google'ı kullanarak uygulamanızda halihazırda oturum açıp açmadığını kontrol edin:GoogleSignIn.silentSignIn() .addOnCompleteListener( this, new OnCompleteListener<GoogleSignInAccount>() { @Override public void onComplete(@NonNull Task<GoogleSignInAccount> task) { handleSignInResult(task); } });
-
Kullanıcı sessizce oturum açamıyorsa kullanıcıya oturum açma seçeneği sunarak normal oturum kapalıyken yaşadığınız deneyimi sunun. Kullanıcı oturum açtığında, oturum açma amacının etkinlik sonucundaki kullanıcının
GoogleSignInAccount
değerini alın:// This task is always completed immediately, there is no need to attach an // asynchronous listener. Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); handleSignInResult(task);
-
Kullanıcı sessizce veya açıkça oturum açtıktan sonra
GoogleSignInAccount
nesnesinden kimlik jetonunu alın:private void handleSignInResult(@NonNull Task<GoogleSignInAccount> completedTask) { try { GoogleSignInAccount account = completedTask.getResult(ApiException.class); String idToken = account.getIdToken(); // TODO(developer): send ID Token to server and validate updateUI(account); } catch (ApiException e) { Log.w(TAG, "handleSignInResult:error", e); updateUI(null); } }
Ardından, kimlik jetonunu sunucunuza bir HTTPS POST isteğiyle gönderin:
HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("https://yourbackend.example.com/tokensignin"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("idToken", idToken)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); final String responseBody = EntityUtils.toString(response.getEntity()); Log.i(TAG, "Signed in as: " + responseBody); } catch (ClientProtocolException e) { Log.e(TAG, "Error sending ID token to backend.", e); } catch (IOException e) { Log.e(TAG, "Error sending ID token to backend.", e); }
Kimlik jetonunun bütünlüğünü doğrulama
Kimlik jetonunu HTTPS POST ile aldıktan sonra jetonun bütünlüğünü doğrulamanız gerekir.
Jetonun geçerli olduğunu doğrulamak için aşağıdaki koşulların sağlandığından emin olun: karşılanıyorsa:
- Kimlik jetonu Google tarafından düzgün bir şekilde imzalandı. Google'ın genel anahtarlarını kullanın
(kullanılabilir
JWK veya
PEM biçimini kullanın)
kullanın. Bu anahtarlar düzenli olarak döndürülür; incelemek
ne zaman olduğunu belirlemek için yanıttaki
Cache-Control
üstbilgisi bunları tekrar almanız gerekir. - Kimlik jetonundaki
aud
değeri, uygulamanızın izin vermiştir. Bu kontrol, kötü amaçlı bir sunucuya kimlik jetonlarının verilmesini önlemek için gereklidir. uygulamanızın arka uç sunucusunda aynı kullanıcıyla ilgili verilere erişmek için kullanılan bir uygulamadır. - Kimlik jetonundaki
iss
değeri şuna eşit:accounts.google.com
veyahttps://accounts.google.com
. - Kimlik jetonunun geçerlilik süresi (
exp
) geçmedi. - Kimlik jetonunun bir Google Workspace veya Cloud'u temsil ettiğini doğrulamanız gerekiyorsa
hd
hak talebini kontrol edebilirsiniz. Bu hak talebi, barındırılan etkinliklerin kullanıcının alanıyla ilişkilidir. Bu, bir kaynağa erişimi yalnızca belirli alan adlarında kullanılabilir. Bu hak talebinin olmaması, hesabın Google tarafından barındırılan alan.
email
, email_verified
ve hd
alanlarını kullanarak aşağıdakilerin geçerli olup olmadığını belirleyebilirsiniz:
Google, e-posta adreslerini barındırır ve bu adres konusunda yetkilidir. Google'ın yetkili olduğu durumlarda
kullanıcının yasal hesap sahibi olduğu biliniyorsa, şifre veya diğer iletişim bilgilerini atlayabilirsiniz.
isteyebilirsiniz.
Google'ın yetkili olduğu durumlar:
email
adresinin@gmail.com
son eki var. Bu bir Gmail hesabı.email_verified
doğru vehd
ayarlandı. Bu bir G Suite hesabı.
Kullanıcılar, Gmail veya G Suite kullanmadan Google Hesaplarına kaydolabilir. Zaman
email
, @gmail.com
son eki içermiyor ve hd
mevcut değilse Google
kimlik doğrulama, şifre veya diğer sorgulama yöntemlerinin önerildiğini doğrulama
gösterir. email_verified
, Google'ın ilk olarak
kullanıcı hesabı sırasında üçüncü tarafın
e-posta hesabı değişmiş olabilir.
Bu doğrulama adımlarını uygulamak için kendi kodunuzu yazmak yerine,
Platformunuz için bir Google API istemci kitaplığı veya genel amaçlı bir
JWT kitaplığı. Geliştirme ve hata ayıklama için tokeninfo
hattımızı arayabilirsiniz
doğrulama uç noktası.
Using a Google API Client Library
Using one of the Google API Client Libraries (e.g. Java, Node.js, PHP, Python) is the recommended way to validate Google ID tokens in a production environment.
To validate an ID token in Java, use the GoogleIdTokenVerifier object. For example:
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 CLIENT_ID of the app that accesses the backend: .setAudience(Collections.singletonList(CLIENT_ID)) // Or, if multiple clients access the backend: //.setAudience(Arrays.asList(CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3)) .build(); // (Receive idTokenString by HTTPS POST) GoogleIdToken idToken = verifier.verify(idTokenString); if (idToken != null) { Payload payload = idToken.getPayload(); // Print user identifier 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."); }
The GoogleIdTokenVerifier.verify()
method verifies the JWT
signature, the aud
claim, the iss
claim, and the
exp
claim.
If you need to validate that the ID token represents a Google Workspace or Cloud
organization account, you can verify the hd
claim by checking the domain name
returned by the Payload.getHostedDomain()
method. The domain of the
email
claim is insufficient to ensure that the account is managed by a domain
or organization.
To validate an ID token in Node.js, use the Google Auth Library for Node.js. Install the library:
npm install google-auth-library --save
verifyIdToken()
function. For example:
const {OAuth2Client} = require('google-auth-library'); const client = new OAuth2Client(); async function verify() { const ticket = await client.verifyIdToken({ idToken: token, audience: CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend // Or, if multiple clients access the backend: //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3] }); const payload = ticket.getPayload(); const userid = payload['sub']; // If the request specified a Google Workspace domain: // const domain = payload['hd']; } verify().catch(console.error);
The verifyIdToken
function verifies
the JWT signature, the aud
claim, the exp
claim,
and the iss
claim.
If you need to validate that the ID token represents a Google Workspace or Cloud
organization account, you can check the hd
claim, 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.
To validate an ID token in PHP, use the Google API Client Library for PHP. Install the library (for example, using Composer):
composer require google/apiclient
verifyIdToken()
function. For example:
require_once 'vendor/autoload.php'; // Get $id_token via HTTPS POST. $client = new Google_Client(['client_id' => $CLIENT_ID]); // Specify the CLIENT_ID of the app that accesses the backend $payload = $client->verifyIdToken($id_token); if ($payload) { $userid = $payload['sub']; // If the request specified a Google Workspace domain //$domain = $payload['hd']; } else { // Invalid ID token }
The verifyIdToken
function verifies
the JWT signature, the aud
claim, the exp
claim,
and the iss
claim.
If you need to validate that the ID token represents a Google Workspace or Cloud
organization account, you can check the hd
claim, 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.
To validate an ID token in Python, use the verify_oauth2_token function. For example:
from google.oauth2 import id_token from google.auth.transport import requests # (Receive token by HTTPS POST) # ... try: # Specify the CLIENT_ID of the app that accesses the backend: idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID) # Or, if multiple clients access the backend server: # idinfo = id_token.verify_oauth2_token(token, requests.Request()) # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, 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. userid = idinfo['sub'] except ValueError: # Invalid token pass
The verify_oauth2_token
function verifies the JWT
signature, the aud
claim, and the exp
claim.
You must also verify the hd
claim (if applicable) by examining the object that
verify_oauth2_token
returns. If multiple clients access the
backend server, also manually verify the aud
claim.
Calling the tokeninfo endpoint
An easy way to validate an ID token signature for debugging is to
use the tokeninfo
endpoint. Calling this endpoint involves an
additional network request that does most of the validation for you while you test proper
validation and payload extraction in your own code. It is not suitable for use in production
code as requests may be throttled or otherwise subject to intermittent errors.
To validate an ID token using the tokeninfo
endpoint, make an HTTPS
POST or GET request to the endpoint, and pass your ID token in the
id_token
parameter.
For example, to validate the token "XYZ123", make the following GET request:
https://oauth2.googleapis.com/tokeninfo?id_token=XYZ123
If the token is properly signed and the iss
and exp
claims have the expected values, you will get a HTTP 200 response, where the body
contains the JSON-formatted ID token claims.
Here's an example response:
{ // These six fields are included in all Google ID Tokens. "iss": "https://accounts.google.com", "sub": "110169484474386276334", "azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com", "aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com", "iat": "1433978353", "exp": "1433981953", // These seven fields are only included when the user has granted the "profile" and // "email" OAuth scopes to the application. "email": "testuser@gmail.com", "email_verified": "true", "name" : "Test User", "picture": "https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg", "given_name": "Test", "family_name": "User", "locale": "en" }
If you need to validate that the ID token represents a Google Workspace account, you can check
the hd
claim, 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 Workspace hosted domain.
Hesap veya oturum oluşturma
Jetonu doğruladıktan sonra, kullanıcının zaten kullanıcı veritabanınızda olup olmadığını kontrol edin. Bu durumda, kullanıcı için kimliği doğrulanmış bir oturum oluşturun. Kullanıcı henüz kullanıcı veritabanınızda değilse kimlik jetonu yükündeki bilgilerden yeni bir kullanıcı kaydı oluşturun ve kullanıcı için oturum oluşturun. Uygulamanızda yeni oluşturulmuş bir kullanıcı tespit ettiğinizde kullanıcıdan ihtiyaç duyduğunuz ek profil bilgilerini girmesini isteyebilirsiniz.
Hesaplar Arası Koruma ile kullanıcılarınızın hesaplarının güvenliğini sağlama
Bir kullanıcının oturum açması için Google'a bağlı olduğunuzda, Google'ın kullanıcı verilerini korumak için oluşturduğu tüm güvenlik özelliklerinden ve altyapıdan otomatik olarak yararlanırsınız. Ancak, çok düşük olasılıkla da olsa kullanıcının Google Hesabı güvenliği ihlal edilirse veya başka önemli güvenlik olayları söz konusuysa uygulamanız saldırıya açık olabilir. Hesaplarınızı büyük güvenlik olaylarına karşı daha iyi korumak için Google'dan güvenlik uyarıları almak üzere Hesaplar Arası Koruma'yı kullanın. Bu etkinlikleri aldığınızda kullanıcının Google Hesabı'nın güvenliğiyle ilgili önemli değişiklikleri görebilirsiniz. Ardından hesaplarınızın güvenliğini sağlamak için hizmetinizde işlem yapabilirsiniz.