OAuth ve Google ile Oturum Açma ile Kolay Bağlantı

Genel bakış

OAuth tabanlı Google Oturum Açma modern bağlantısı, Google ile Oturum Açma'yı OAuth bağlantısının üzerine ekler. Bu, Google kullanıcıları için sorunsuz bir bağlantı deneyimi sağlar ve kullanıcının Google hesabını kullanarak hizmetinizde yeni bir hesap oluşturmasına olanak tanıyan hesap oluşturma özelliğini de sağlar.

OAuth ve Google ile Oturum Açma özelliğini kullanarak hesap bağlama işlemi gerçekleştirmek için aşağıdaki genel adımları uygulayın:

  1. İlk olarak, kullanıcıdan Google profiline erişim izni vermesini isteyin.
  2. Kullanıcı hesabının mevcut olup olmadığını kontrol etmek için profilindeki bilgileri kullanın.
  3. Mevcut kullanıcılar için hesapları bağlayın.
  4. Kimlik doğrulama sisteminizde Google kullanıcısı için bir eşleşme bulamazsanız Google'dan alınan kimlik jetonunu doğrulayın. Daha sonra, kimlik jetonunda bulunan profil bilgilerine göre bir kullanıcı oluşturabilirsiniz.
Bu şekilde, basitleştirilmiş bağlantı akışı ile kullanıcının Google hesabını bağlaması için adımlar gösterilmektedir. İlk ekran görüntüsünde, kullanıcıların uygulamanızı bağlamak için nasıl seçebileceği gösteriliyor. İkinci ekran görüntüsü, kullanıcının hizmetinizde mevcut bir hesaba sahip olup olmadığını onaylamasını sağlar. Üçüncü ekran görüntüsünde ise kullanıcının, bağlamak istediği Google hesabını seçmesi mümkün. Dördüncü ekran görüntüsünde, Google hesabını uygulamanıza bağlamayla ilgili onay gösteriliyor. Beşinci ekran görüntüsünde, Google uygulamasında başarılı bir şekilde bağlı kullanıcı hesabı gösteriliyor.

Şekil 1. Sorunsuz bağlantı ile kullanıcının telefonunda hesap bağlama

Modern Bağlantı Gereksinimleri

OAuth sunucunuzu uygulama

Jeton değişimi uç noktanızın check, create, get amaçlarını desteklemesi gerekir. Aşağıda, hesap bağlama akışı boyunca tamamlanan adımlar ve farklı amaçların ne zaman çağrıldığı gösterilmektedir:

  1. Kullanıcının kimlik doğrulama sisteminizde hesabı var mı? (Kullanıcı YES veya NO'yu seçerek karar verir)
    1. EVET : Kullanıcı, platformunuzda oturum açmak için Google hesabıyla ilişkili e-posta adresini kullanıyor mu? (Kullanıcı YES veya NO'yu seçerek karar verir)
      1. EVET : Kimlik doğrulama sisteminizde eşleşen bir hesap var mı? (check intent numaralı telefonu arayarak arayın)
        1. EVET : get intent aranır ve istek başarıyla döndürülürse hesap bağlanır.
        2. HAYIR : Yeni Hesap Oluşturulsun mu? (Kullanıcı YES veya NO'yu seçerek karar verir)
          1. EVET : create intent aranır ve oluşturma amacı başarılı olursa hesap bağlanır.
          2. HAYIR : Web OAuth akışı tetiklenir, kullanıcı tarayıcısına yönlendirilir ve kullanıcıya farklı bir e-posta ile bağlantı oluşturma seçeneği sunulur.
      2. HAYIR : Web OAuth akışı tetiklenir, kullanıcı tarayıcısına yönlendirilir ve kullanıcıya farklı bir e-posta ile bağlanma seçeneği sunulur.
    2. HAYIR : Kimlik doğrulama sisteminizde eşleşen bir kullanıcı var mı? (check intent numaralı telefonu arayarak arayın)
      1. EVET : get intent aranır ve istek başarıyla döndürülürse hesap bağlanır.
      2. HAYIR : create intent aranır ve oluşturma amacı başarıyla döndürülürse hesap bağlanır.

Mevcut bir kullanıcı hesabını kontrol etme (amacı kontrol edin)

Kullanıcı, Google profiline erişim izni verdikten sonra Google, kullanıcının Google imzalı kimliğini içeren bir istek gönderir. Bu yorum, kullanıcının Google Hesap Kimliği, adı ve e-posta adresini içeren bilgileri içerir. Projeniz için yapılandırılan jeton değişimi uç noktası bu isteği işler.

Kimlik doğrulama sisteminizde karşılık gelen Google hesabı zaten varsa jeton değişimi uç noktanız account_found=true ile yanıt verir. Google hesabı mevcut bir kullanıcıyla eşleşmezse jeton Exchange uç noktanız, account_found=false ile HTTP 404 Bulunamadı hatası döndürür.

İstek aşağıdaki biçimdedir:

POST /token HTTP/1.1
Host: oauth2.example.com
Content-Type: application/x-www-form-urlencoded

grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&intent=check&assertion=JWT&scope=SCOPES&client_id=GOOGLE_CLIENT_ID&client_secret=GOOGLE_CLIENT_SECRET

Jeton değişimi uç noktanız aşağıdaki parametreleri işleyebilmelidir:

Jeton uç nokta parametreleri
intent Bu istekler için bu parametrenin değeri check olur.
grant_type Alınan jetonun türü. Bu istekler için bu parametre urn:ietf:params:oauth:grant-type:jwt-bearer değerine sahiptir.
assertion Google kullanıcı kimliğinin imzalı bir onayını sağlayan bir JSON Web Jetonu (JWT). JWT, kullanıcının Google Hesabı kimliğini, adını ve e-posta adresini içeren bilgileri içerir.
client_id Google'a atadığınız istemci kimliği.
client_secret Google'a atadığınız istemci gizli anahtarı.

check intent isteklerine yanıt vermek için jeton Exchange uç noktanızın aşağıdaki adımları gerçekleştirmesi gerekir:

  • JWT onayını doğrulayın ve kodunu çözün.
  • Kimlik doğrulama sisteminizde Google hesabının zaten mevcut olup olmadığını kontrol edin.
Validate and decode the JWT assertion

You can validate and decode the JWT assertion by using a JWT-decoding library for your language. Use Google's public keys, available in JWK or PEM formats, to verify the token's signature.

When decoded, the JWT assertion looks like the following example:

{
  "sub": "1234567890",      // The unique ID of the user's Google Account
  "iss": "https://accounts.google.com",        // The assertion's issuer
  "aud": "123-abc.apps.googleusercontent.com", // Your server's client ID
  "iat": 233366400,         // Unix timestamp of the assertion's creation time
  "exp": 233370000,         // Unix timestamp of the assertion's expiration time
  "name": "Jan Jansen",
  "given_name": "Jan",
  "family_name": "Jansen",
  "email": "jan@gmail.com", // If present, the user's email address
  "email_verified": true,   // true, if Google has verified the email address
  "hd": "example.com",      // If present, the host domain of the user's GSuite email address
                            // If present, a URL to user's profile picture
  "picture": "https://lh3.googleusercontent.com/a-/AOh14GjlTnZKHAeb94A-FmEbwZv7uJD986VOF1mJGb2YYQ",
  "locale": "en_US"         // User's locale, from browser or phone settings
}

In addition to verifying the token's signature, verify that the assertion's issuer (iss field) is https://accounts.google.com, that the audience (aud field) is your assigned client ID, and that the token has not expired (exp field).

Using the email, email_verified and hd fields you can determine if Google hosts and is authoritative for an email address. In cases where Google is authoritative the user is currently known to be the legitimate account owner and you may skip password or other challenges methods. Otherwise, these methods can be used to verify the account prior to linking.

Cases where Google is authoritative:

  • email has a @gmail.com suffix, this is a Gmail account.
  • email_verified is true and hd is set, this is a G Suite account.

Users may register for Google Accounts without using Gmail or G Suite. When email does not contain a @gmail.com suffix and hd is absent Google is not authoritative and password or other challenge methods are recommended to verify the user. email_verfied can 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.

Kimlik doğrulama sisteminizde Google hesabının zaten mevcut olup olmadığını kontrol etme

Aşağıdaki koşullardan birinin doğru olup olmadığını kontrol edin:

  • Onaylamanın sub alanında bulunan Google Hesap Kimliği, kullanıcı veritabanınızdadır.
  • Onaylamadaki e-posta adresi, kullanıcı veritabanınızdaki bir kullanıcıyla eşleşiyor.

İki koşuldan biri doğruysa kullanıcı zaten kaydolmuştur. Bu durumda aşağıdakine benzer bir yanıt verin:

HTTP/1.1 200 Success
Content-Type: application/json;charset=UTF-8

{
  "account_found":"true",
}

Açıklamada belirtilen Google Hesabı Kimliği veya e-posta adresi veritabanınızdaki bir kullanıcıyla eşleşmiyorsa kullanıcı henüz kaydolmamıştır. Bu durumda, jeton değişimi uç noktanızın aşağıdaki örnekte olduğu gibi "account_found": "false" belirten bir HTTP 404 hatasıyla yanıt vermesi gerekir:

HTTP/1.1 404 Not found
Content-Type: application/json;charset=UTF-8

{
  "account_found":"false",
}

Handle automatic linking (get intent)

After the user gives consent to access their Google profile, Google sends a request that contains a signed assertion of the Google user's identity. The assertion contains information that includes the user's Google Account ID, name, and email address. The token exchange endpoint configured for your project handles that request.

If the corresponding Google Account is already present in your authentication system, your token exchange endpoint returns a token for the user. If the Google Account doesn't match an existing user, your token exchange endpoint returns a linking_error error and optional login_hint.

The request has the following form:

POST /token HTTP/1.1
Host: oauth2.example.com
Content-Type: application/x-www-form-urlencoded

grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&intent=get&assertion=JWT&scope=SCOPES&client_id=GOOGLE_CLIENT_ID&client_secret=GOOGLE_CLIENT_SECRET

Your token exchange endpoint must be able to handle the following parameters:

Token endpoint parameters
intent For these requests, the value of this parameter is get.
grant_type The type of token being exchanged. For these requests, this parameter has the value urn:ietf:params:oauth:grant-type:jwt-bearer.
assertion A JSON Web Token (JWT) that provides a signed assertion of the Google user's identity. The JWT contains information that includes the user's Google Account ID, name, and email address.
scope Optional: Any scopes that you've configured Google to request from users.
client_id The client ID you assigned to Google.
client_secret The client secret you assigned to Google.

To respond to the get intent requests, your token exchange endpoint must perform the following steps:

  • Validate and decode the JWT assertion.
  • Check if the Google account is already present in your authentication system.
Validate and decode the JWT assertion

You can validate and decode the JWT assertion by using a JWT-decoding library for your language. Use Google's public keys, available in JWK or PEM formats, to verify the token's signature.

When decoded, the JWT assertion looks like the following example:

{
  "sub": "1234567890",      // The unique ID of the user's Google Account
  "iss": "https://accounts.google.com",        // The assertion's issuer
  "aud": "123-abc.apps.googleusercontent.com", // Your server's client ID
  "iat": 233366400,         // Unix timestamp of the assertion's creation time
  "exp": 233370000,         // Unix timestamp of the assertion's expiration time
  "name": "Jan Jansen",
  "given_name": "Jan",
  "family_name": "Jansen",
  "email": "jan@gmail.com", // If present, the user's email address
  "email_verified": true,   // true, if Google has verified the email address
  "hd": "example.com",      // If present, the host domain of the user's GSuite email address
                            // If present, a URL to user's profile picture
  "picture": "https://lh3.googleusercontent.com/a-/AOh14GjlTnZKHAeb94A-FmEbwZv7uJD986VOF1mJGb2YYQ",
  "locale": "en_US"         // User's locale, from browser or phone settings
}

In addition to verifying the token's signature, verify that the assertion's issuer (iss field) is https://accounts.google.com, that the audience (aud field) is your assigned client ID, and that the token has not expired (exp field).

Using the email, email_verified and hd fields you can determine if Google hosts and is authoritative for an email address. In cases where Google is authoritative the user is currently known to be the legitimate account owner and you may skip password or other challenges methods. Otherwise, these methods can be used to verify the account prior to linking.

Cases where Google is authoritative:

  • email has a @gmail.com suffix, this is a Gmail account.
  • email_verified is true and hd is set, this is a G Suite account.

Users may register for Google Accounts without using Gmail or G Suite. When email does not contain a @gmail.com suffix and hd is absent Google is not authoritative and password or other challenge methods are recommended to verify the user. email_verfied can 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.

Check if the Google account is already present in your authentication system

Check whether either of the following conditions are true:

  • The Google Account ID, found in the assertion's sub field, is in your user database.
  • The email address in the assertion matches a user in your user database.

If an account is found for the user, issue an access token and return the values in a JSON object in the body of your HTTPS response, like in the following example:

{
  "token_type": "Bearer",
  "access_token": "ACCESS_TOKEN",

  "expires_in": SECONDS_TO_EXPIRATION
}

In some cases, account linking based on ID token might fail for the user. If it does so for any reason, your token exchange endpoint needs to reply with a HTTP 401 error that specifies error=linking_error, as the following example shows:

HTTP/1.1 401 Unauthorized
Content-Type: application/json;charset=UTF-8

{
  "error":"linking_error",
  "login_hint":"foo@bar.com"
}

When Google receives a 401 error response with linking_error, Google sends the user to your authorization endpoint with login_hint as a parameter. The user completes account linking using the OAuth linking flow in their browser.

Handle account creation via Google Sign-In (create intent)

When a user needs to create an account on your service, Google makes a request to your token exchange endpoint that specifies intent=create.

The request has the following form:

POST /token HTTP/1.1
Host: oauth2.example.com
Content-Type: application/x-www-form-urlencoded

response_type=token&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&scope=SCOPES&intent=create&assertion=JWT&client_id=GOOGLE_CLIENT_ID&client_secret=GOOGLE_CLIENT_SECRET

Your token exchange endpoint must able to handle the following parameters:

Token endpoint parameters
intent For these requests, the value of this parameter is create.
grant_type The type of token being exchanged. For these requests, this parameter has the value urn:ietf:params:oauth:grant-type:jwt-bearer.
assertion A JSON Web Token (JWT) that provides a signed assertion of the Google user's identity. The JWT contains information that includes the user's Google Account ID, name, and email address.
client_id The client ID you assigned to Google.
client_secret The client secret you assigned to Google.

The JWT within the assertion parameter contains the user's Google Account ID, name, and email address, which you can use to create a new account on your service.

To respond to the create intent requests, your token exchange endpoint must perform the following steps:

  • Validate and decode the JWT assertion.
  • Validate user information and create new account.
Validate and decode the JWT assertion

You can validate and decode the JWT assertion by using a JWT-decoding library for your language. Use Google's public keys, available in JWK or PEM formats, to verify the token's signature.

When decoded, the JWT assertion looks like the following example:

{
  "sub": "1234567890",      // The unique ID of the user's Google Account
  "iss": "https://accounts.google.com",        // The assertion's issuer
  "aud": "123-abc.apps.googleusercontent.com", // Your server's client ID
  "iat": 233366400,         // Unix timestamp of the assertion's creation time
  "exp": 233370000,         // Unix timestamp of the assertion's expiration time
  "name": "Jan Jansen",
  "given_name": "Jan",
  "family_name": "Jansen",
  "email": "jan@gmail.com", // If present, the user's email address
  "email_verified": true,   // true, if Google has verified the email address
  "hd": "example.com",      // If present, the host domain of the user's GSuite email address
                            // If present, a URL to user's profile picture
  "picture": "https://lh3.googleusercontent.com/a-/AOh14GjlTnZKHAeb94A-FmEbwZv7uJD986VOF1mJGb2YYQ",
  "locale": "en_US"         // User's locale, from browser or phone settings
}

In addition to verifying the token's signature, verify that the assertion's issuer (iss field) is https://accounts.google.com, that the audience (aud field) is your assigned client ID, and that the token has not expired (exp field).

Using the email, email_verified and hd fields you can determine if Google hosts and is authoritative for an email address. In cases where Google is authoritative the user is currently known to be the legitimate account owner and you may skip password or other challenges methods. Otherwise, these methods can be used to verify the account prior to linking.

Cases where Google is authoritative:

  • email has a @gmail.com suffix, this is a Gmail account.
  • email_verified is true and hd is set, this is a G Suite account.

Users may register for Google Accounts without using Gmail or G Suite. When email does not contain a @gmail.com suffix and hd is absent Google is not authoritative and password or other challenge methods are recommended to verify the user. email_verfied can 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.

Validate user information and create new account

Check whether either of the following conditions are true:

  • The Google Account ID, found in the assertion's sub field, is in your user database.
  • The email address in the assertion matches a user in your user database.

If either condition is true, prompt the user to link their existing account with their Google Account. To do so, respond to the request with an HTTP 401 error that specifies error=linking_error and gives the user's email address as the login_hint. The following is a sample response:

HTTP/1.1 401 Unauthorized
Content-Type: application/json;charset=UTF-8

{
  "error":"linking_error",
  "login_hint":"foo@bar.com"
}

When Google receives a 401 error response with linking_error, Google sends the user to your authorization endpoint with login_hint as a parameter. The user completes account linking using the OAuth linking flow in their browser.

If neither condition is true, create a new user account with the information provided in the JWT. New accounts don't typically have a password set. It's recommended that you add Google Sign-In to other platforms to enable users to log in with Google across the surfaces of your application. Alternatively, you can email the user a link that starts your password recovery flow to allow the user to set a password to sign in on other platforms.

When the creation is completed, issue an access token and return the values in a JSON object in the body of your HTTPS response, like in the following example:

{
  "token_type": "Bearer",
  "access_token": "ACCESS_TOKEN",

  "expires_in": SECONDS_TO_EXPIRATION
}

Google API İstemci Kimliğinizi alma

Hesap Bağlama kayıt işlemi sırasında Google API İstemci Kimliğinizi sağlamanız gerekecektir.

OAuth Bağlantısı adımlarını tamamlarken oluşturduğunuz projeyi kullanarak API İstemci Kimliğinizi almak için. Bunun için aşağıdaki adımları uygulayın:

  1. Google API konsolunun Kimlik bilgileri sayfasını açın.
  2. Bir Google API'leri projesi oluşturun veya seçin.

    Projenizin Web uygulaması türü için istemci kimliği yoksa bir kimlik oluşturmak için Kimlik bilgisi oluştur ve OAuth istemci kimliği'ni tıklayın. Sitenizin alanını Yetkili JavaScript kaynakları kutusuna eklediğinizden emin olun. Yerel testler veya geliştirme gerçekleştirirken Yetkili JavaScript kaynakları alanına hem http://localhost hem de http://localhost:<port_number> eklemeniz gerekir.

Uygulamanızı doğrulama

Sen kullanarak uygulanmasını doğrulamak OAuth 2.0 Bahçesi aracı.

Araçta aşağıdaki adımları uygulayın:

  1. Yapılandırma tıklayın OAuth 2.0 Yapılandırma penceresini açın.
  2. OAuth akış alanında, istemci tarafı seçin.
  3. OAuth Endpoints alanında, Özel'i seçin.
  4. OAuth 2.0 uç noktanızı ve Google'a atadığınız müşteri kimliğini ilgili alanlarda belirtin.
  5. Adım 1 bölümünde, herhangi bir Google kapsamları seçmeyin. Bunun yerine, bu alanı boş bırakın veya sunucunuz için geçerli bir kapsam (veya OAuth kapsamları kullanmıyorsanız rastgele bir dize) yazın. İşiniz bittiğinde, Yetkilendirme API'leri tıklayın.
  6. Aşama 2 ile Aşama 3 bölümlerde OAuth 2.0 akışı geçmesi ve istendiği gibi her aşama çalıştığını doğrulamak.

Sen kullanarak uygulanmasını doğrulamak Google Hesap Bağlama Demo aracı.

Araçta aşağıdaki adımları uygulayın:

  1. Oturum Google düğmesiyle tıklayın.
  2. Bağlamak istediğiniz hesabı seçin.
  3. Hizmet kimliğini girin.
  4. İsteğe bağlı olarak, erişim isteyeceğiniz bir veya daha fazla kapsam girin.
  5. Başlangıç Demo tıklayın.
  6. İstendiğinde, bağlantı isteğini kabul edip reddedebileceğinizi onaylayın.
  7. Platformunuza yönlendirildiğinizi onaylayın.