OAuth ve Google ile Oturum Açma ile hesap bağlama (Dialogflow)

OAuth ve Google ile Oturum Açma bağlantı türü, OAuth tabanlı yöntemlere ek olarak Google ile Oturum Açma özelliğini ekler. hesap bağlama. Bu, Google kullanıcıları için sorunsuz, ses tabanlı bağlantı sağlar aynı zamanda hizmetinize kaydolan kullanıcılar için hesap bağlamayı etkinleştirir Google dışı bir kimlikle oturum açın.

Bu bağlantı türü, Google ile Oturum Açma özelliğiyle başlar. Google ile Oturum Açma, kullanıcının Google profil bilgileri sisteminizde mevcut. Kullanıcının bilgileri bulunamadığından, standart bir OAuth akışı başlar. Kullanıcı ayrıca Google profil bilgileriyle yeni bir hesap oluşturmayı seçebilir.

Şekil 1: İşleminiz kullanıcının Google bu etiketi, kimlik doğrulama sisteminizdeki kullanıcıyla ilgili bir eşleşme bulmak için kullanabilirsiniz.

OAuth ve Google ile Oturum Açma ile hesap bağlama işlemi gerçekleştirmek için aşağıdaki genel talimatları uygulayın. için şu adımları izleyin:

  1. İlk olarak kullanıcıdan Google profiline erişim izni vermesini isteyin.
  2. Kullanıcıyı tanımlamak için profilindeki bilgileri kullanın.
  3. Kimlik doğrulama sisteminizde Google kullanıcısı için eşleşme bulamıyorsanız akış, Actions projenizi yapılandırıp yapılandırmadığınıza bağlı olarak devam eder Sesle veya yalnızca açık olarak kullanıcı hesabı oluşturulmasına izin vermek için Actions konsolunda sitenizi ziyaret edin.
    • Sesle hesap oluşturmaya izin verirseniz kimliği doğrulayın Google'dan alınan simge. Daha sonra, kullandığınız kimlik jetonunda bulunan profil bilgilerini sağlayın.
    • Sesle hesap oluşturulmasına izin vermezseniz kullanıcı şuraya aktarılır: bir tarayıcı kullanarak yetkilendirme sayfanızı yükleyip kullanıcıyı içerik üretme akışıyla ilgilidir.
ziyaret edin.
Sesle hesap oluşturmaya izin verirseniz ve için bir eşleşme bulamıyorsanız
            kimlik doğrulama sisteminizdeki Google profilini seçerseniz
            Google'dan alınan kimlik jetonunu doğrulayın. Ardından, oluşturduğunuz
            kullanıcı değerini (kimlik jetonunda bulunan profil bilgilerine göre) gösterir.
            Sesle kullanıcı hesabı oluşturulmasına izin vermezseniz kullanıcı:
            İzin verme sayfanızı yükleyebilecekleri bir tarayıcıya aktarılır
            ve akışı tamamlayın.
Şekil 2. OAuth ve Google'ın görsel bir temsili Bir kullanıcının bilgileri sisteminizde bulunamadığında gerçekleşen oturum açma akışı.

Sesle hesap oluşturmayı destekleyin

Sesle kullanıcı hesabı oluşturulmasına izin verirseniz Asistan, kullanıcıya şunları yapmak istiyorlar:

  • Google hesap bilgilerini kullanarak sisteminizde yeni bir hesap oluşturun veya
  • Varsa kimlik doğrulama sisteminizde farklı bir hesapla oturum açın. mevcut bir Google dışı hesabınız olabilir.

soruna neden olabilir. Kullanıcının yalnızca ses akışını bırakması gerekir Mevcut bir Google dışı hesabını kullanarak oturum açmak istiyorlarsa.

Sesle hesap oluşturmaya izin verme

Sesle kullanıcı hesabı oluşturulmasına izin vermediyseniz Asistan kullanıcı kimlik doğrulaması için sağladığınız web sitesi. Etkileşim gerçekleşiyorsa ekranı olmayan bir cihazda; Asistan, kullanıcıyı telefona yönlendirirse devam edin.

Oluşturmaya izin vermemeniz şu durumlarda önerilir:

  • Google dışı hesapları olan kullanıcıların yeni bir hesap oluşturmasına izin vermek istemiyorsanız ve hesabınızındaki mevcut kullanıcı hesaplarına bağlanmasını istiyorsanız kimlik doğrulama sistemi kullanır. Örneğin, bir bağlılık programı sunuyorsanız kullanıcının puanlarını kaybetmediğinden emin olmak isteyebilirsiniz. mevcut hesabınızda oturum açın.

  • Hesap oluşturma akışı üzerinde tam kontrole sahip olmanız gerekir. Örneğin herkesin sırasında kullanıcıya hizmet şartlarınızı göstermeniz gerekiyorsa içerik oluşturulmasına izin vermeme hesap oluşturma.

ziyaret edin.

OAuth ve Google ile Oturum Açma hesap bağlamayı uygulama

Hesaplar, endüstri standardı OAuth 2.0 akışlarına bağlıdır. Actions on Google, örtülü ve yetkilendirme kod akışlarını destekler.

Dolaylı kod akışında Google, yetkilendirme uç noktanızı kullanıcının tarayıcısında açar. Başarılı bir şekilde oturum açtıktan sonra Google'a uzun ömürlü bir erişim jetonu döndürürsünüz. Bu erişim jetonu artık Asistan'dan Action'ınıza gönderilen her isteğe dahil edilir.

Yetkilendirme kodu akışında iki uç noktaya ihtiyacınız vardır:

  • Oturum açma kullanıcı arayüzünü henüz oturum açmamış kullanıcılara sunmaktan ve istenen erişime kısa süreli bir yetkilendirme kodu biçiminde izin kaydetmekten sorumlu olan yetkilendirme uç noktası.
  • İki tür exchange'den sorumlu olan jeton değişimi uç noktası:
    1. Yetkilendirme kodunu uzun ömürlü yenileme jetonu ve kısa ömürlü erişim jetonu ile değiştirir. Bu değişim, kullanıcı hesap bağlama akışından geçer.
    2. Kısa ömürlü bir erişim jetonu için uzun süreli yenileme jetonunu değiştirir. Bu exchange, Google'ın süresi dolmuş olduğundan yeni bir erişim jetonuna ihtiyacı olduğunda gerçekleşir.

Örtülü akış kullanılarak verilen erişim jetonlarının geçerlilik süresinin hiçbir zaman dolmaması, Google'ın örtülü akışla kullanılması nedeniyle kullanıcının hesabını tekrar bağlamayı zorunlu kıldığı için Google, örtülü akış akışının uygulanmasını önerir. Güvenlik nedeniyle jetonun süresinin dolması gerekiyorsa kimlik doğrulama kodu akışını kullanmanız önerilir.

Projeyi yapılandırma

Projenizi OAuth ve Google ile Oturum Açma hesabını kullanacak şekilde yapılandırmak için aşağıdaki adımları uygulayın:

  1. Actions konsolunu açın ve kullanmak istediğiniz projeyi seçin.
  2. Geliştir sekmesini tıklayıp Hesap bağlama'yı seçin.
  3. Hesap bağlama'nın yanındaki anahtarı etkinleştirin.
  4. Hesap oluşturma bölümünde Evet'i seçin.

  5. Bağlantı türü'nde OAuth ve Google ile Oturum Açma ve Dolaylı.

  6. İstemci Bilgileri bölümünde aşağıdakileri yapın:

    • Aşağıdakileri belirlemek için Actions'ınız tarafından Google'a verilen Client-ID'ye Google'dan gelen isteklerle karşılaşıyorum.
    • Yetkilendirme ve Token Exchange uç noktalarınızın URL'lerini ekleyin.
  7. Kaydet'i tıklayın.

OAuth sunucunuzu uygulama

To support the OAuth 2.0 implicit flow, your service makes an authorization endpoint available by HTTPS. This endpoint is responsible for authenticating and obtaining consent from users for data access. The authorization endpoint presents a sign-in UI to your users that aren't already signed in and records consent to the requested access.

When your Action needs to call one of your service's authorized APIs, Google uses this endpoint to get permission from your users to call these APIs on their behalf.

A typical OAuth 2.0 implicit flow session initiated by Google has the following flow:

  1. Google opens your authorization endpoint in the user's browser. The user signs in if not signed in already, and grants Google permission to access their data with your API if they haven't already granted permission.
  2. Your service creates an access token and returns it to Google by redirecting the user's browser back to Google with the access token attached to the request.
  3. Google calls your service's APIs, and attaches the access token with each request. Your service verifies that the access token grants Google authorization to access the API and then completes the API call.

Handle authorization requests

When your Action needs to perform account linking via an OAuth2 implicit flow, Google sends the user to your authorization endpoint with a request that includes the following parameters:

Authorization endpoint parameters
client_id The client ID you assigned to Google.
redirect_uri The URL to which you send the response to this request.
state A bookkeeping value that is passed back to Google unchanged in the redirect URI.
response_type The type of value to return in the response. For the OAuth 2.0 implicit flow, the response type is always token.

For example, if your authorization endpoint is available at https://myservice.example.com/auth, a request might look like:

GET https://myservice.example.com/auth?client_id=GOOGLE_CLIENT_ID&redirect_uri=REDIRECT_URI&state=STATE_STRING&response_type=token

For your authorization endpoint to handle sign-in requests, do the following steps:

  1. Verify the client_id and redirect_uri values to prevent granting access to unintended or misconfigured client apps:

    • Confirm that the client_id matches the client ID you assigned to Google.
    • Confirm that the URL specified by the redirect_uri parameter has the following form:
      https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID
      YOUR_PROJECT_ID is the ID found on the Project settings page of the Actions Console.
  2. Check if the user is signed in to your service. If the user isn't signed in, complete your service's sign-in or sign-up flow.

  3. Generate an access token that Google will use to access your API. The access token can be any string value, but it must uniquely represent the user and the client the token is for and must not be guessable.

  4. Send an HTTP response that redirects the user's browser to the URL specified by the redirect_uri parameter. Include all of the following parameters in the URL fragment:

    • access_token: the access token you just generated
    • token_type: the string bearer
    • state: the unmodified state value from the original request The following is an example of the resulting URL:
      https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID#access_token=ACCESS_TOKEN&token_type=bearer&state=STATE_STRING

Google's OAuth 2.0 redirect handler will receive the access token and confirm that the state value hasn't changed. After Google has obtained an access token for your service, Google will attach the token to subsequent calls to your Action as part of the AppRequest.

Otomatik bağlama işlemini gerçekleştirme

Kullanıcı Google profiline erişmesi için İşleminize izin verdikten sonra, Google Google kullanıcısının kimliği için imzalı bir onay içeren istek gönderir. Onaylama; kullanıcının Google Hesabı kimliğini, adını, ve e-posta adresi. Projenizin işleyicileri için yapılandırılan jeton değişimi uç noktası söz konusu istekte bulunabilirsiniz.

İlgili Google Hesabı kimlik doğrulama sisteminizde zaten varsa jeton değişimi uç noktanız, kullanıcı için bir jeton döndürür. Google Hesabı mevcut bir kullanıcıyla eşleşirse jeton değişimi uç noktanız user_not_found hatası döndürüyor.

Talep 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=get&assertion=JWT&consent_code=CONSENT_CODE&scope=SCOPES

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

Jeton uç noktası parametreleri
grant_type Değişen jetonun türü. Söz konusu parametresi urn:ietf:params:oauth:grant-type:jwt-bearer değerine sahiptir.
intent Bu istekler için parametrenin değeri "get" şeklindedir.
assertion Google Cloud konsolunun imzalı onayını sağlayan bir JSON Web Token (JWT) kullanıcı kimliği. JWT, kullanıcının Google Hesap kimliği, ad ve e-posta adresi.
consent_code İsteğe bağlı: Varsa kullanıcı, işleminizin belirtilen kapsamlara erişmesine izin verdi.
scope İsteğe bağlı: Google'ın kullanıcılardan isteyeceği şekilde yapılandırdığınız kapsamlar.

Jeton değişimi uç noktanız bağlantı isteğini aldığında takip etmek için:

JWT onayını doğrulama ve kodunu çözme

Diliniz için JWT kod çözme kitaplığı kullanarak JWT onayını doğrulayıp kodunu çözebilirsiniz. Google'ın genel anahtarlarını kullanın (JWK veya PEM biçimini) kullanarak jetonun imzası var.

Kodu çözüldüğünde JWT onayı aşağıdaki örnek gibi görünür:

{
  "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
  "locale": "en_US"
}

Jetonun imzasını doğrulamanın yanı sıra onaylamayı verenin de (iss alanı) https://accounts.google.com ve kitle (aud alanı) İşleminize atanan istemci kimliğidir.

Google Hesabı'nın kimlik doğrulama sisteminizde olup olmadığını kontrol edin

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

  • Onaylamanın sub alanında bulunan Google Hesabı kimliği, kullanıcı veritabanınızda yer alır.
  • Onaylamadaki e-posta adresi, kullanıcı veritabanınızdaki bir kullanıcıyla eşleşiyor.

İki koşul da doğruysa kullanıcı zaten kaydolmuş demektir. erişim jetonu.

Onaylamada belirtilmeyen Google Hesabı kimliği veya e-posta adresi veritabanınızdaki bir kullanıcıyla eşleşiyorsa kullanıcı henüz kaydolmamış. Bu durumda, jeton değişimi uç noktası, error=user_not_found değerini belirten bir HTTP 401 hatasıyla yanıt vermelidir aşağıdaki örnekte olduğu gibi:

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

{
  "error":"user_not_found",
}
. Google, user_not_found hatası içeren 401 hatası yanıtı aldığında, Google jeton değişimi uç noktanızı intent parametresinin değeriyle çağırır create olarak ayarlanmış ve kullanıcının profil bilgilerini içeren bir kimlik jetonu gönderiyor işleme koyacağız.

Handle account creation via Google Sign-In

When a user needs to create an account on your service, Google makes a request to your token exchange endpoint that specifies intent=create, as in the following example:

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&consent_code=CONSENT_CODE&assertion=JWT[&NEW_ACCOUNT_INFO]

The assertion parameter contains 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, which you can use to create a new account on your service.

To respond to account creation requests, your token exchange endpoint must do the following:

JWT onayını doğrulama ve kodunu çözme

Diliniz için JWT kod çözme kitaplığı kullanarak JWT onayını doğrulayıp kodunu çözebilirsiniz. Google'ın genel anahtarlarını kullanın (JWK veya PEM biçimini) kullanarak jetonun imzası var.

Kodu çözüldüğünde JWT onayı aşağıdaki örnek gibi görünür:

{
  "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
  "locale": "en_US"
}

Jetonun imzasını doğrulamanın yanı sıra onaylamayı verenin de (iss alanı) https://accounts.google.com ve kitle (aud alanı) İşleminize atanan istemci kimliğidir.

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 by responding to the request with an HTTP 401 error, specifying error=linking_error and the user's email address as the login_hint, as in the following example:

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

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

If neither condition is true, create a new user account using the information provided in the JWT. New accounts do not typically have a password set. It is recommended that you add Google Sign In to other platforms to enable users to log in via 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 for signing 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
}

Kimlik doğrulama akışını başlat

Hesapta Oturum Açma yardımcı amacını kullanma kimlik doğrulama akışını başlatın.

Dialogflow (Node.js)
const app = dialogflow({
  // REPLACE THE PLACEHOLDER WITH THE CLIENT_ID OF YOUR ACTIONS PROJECT
  clientId: CLIENT_ID,
})

// Intent that starts the account linking flow.
app.intent('Start Signin', conv => {
  conv.ask(new SignIn('To get your account details'))
})
Dialogflow (Java)
private String clientId = "<your_client_id>";

@ForIntent("Start Signin")
public ActionResponse text(ActionRequest request) {
  ResponseBuilder rb = getResponseBuilder(request);
  return rb.add(new SignIn().setContext("To get your account details")).build();
}
İşlemler SDK'sı (Node.js)
const app = actionssdk({
  clientId: CLIENT_ID,
})

app.intent('Start Signin', conv => {
  conv.ask(new SignIn('To get your account details'))
})
Actions SDK (Java)
private String clientId = "<your_client_id>";

@ForIntent("actions.intent.TEXT")
public ActionResponse text(ActionRequest request) {
  ResponseBuilder rb = getResponseBuilder(request);
  return rb.add(new SignIn().setContext("To get your account details")).build();
}

Veri erişimi isteklerini işleme

Asistan isteği bir erişim jetonu içeriyorsa: önce erişim jetonunun geçerli olduğundan ve süresinin dolmadığından emin olun, ardından kullanıcı hesabı veritabanı, jetonla ilişkilendirilen kullanıcı hesabı.