OAuth를 사용한 Google 계정 연결

계정은 업계 표준 OAuth 2.0 암시적승인 코드 흐름을 사용하여 연결됩니다. 서비스에서 OAuth 2.0을 준수하는 승인토큰 교환 엔드포인트를 지원해야 합니다.

In the implicit flow, Google opens your authorization endpoint in the user's browser. After successful sign in, you return a long-lived access token to Google. This access token is now included in every request sent from Google.

In the authorization code flow, you need two endpoints:

  • The authorization endpoint, which presents the sign-in UI to your users that aren't already signed in. The authorization endpoint also creates a short-lived authorization code to record users' consent to the requested access.

  • The token exchange endpoint, which is responsible for two types of exchanges:

    1. Exchanges an authorization code for a long-lived refresh token and a short-lived access token. This exchange happens when the user goes through the account linking flow.
    2. Exchanges a long-lived refresh token for a short-lived access token. This exchange happens when Google needs a new access token because the one it had expired.

Choose an OAuth 2.0 flow

Although the implicit flow is simpler to implement, Google recommends that access tokens issued by the implicit flow never expire. This is because the user is forced to link their account again after a token expires with the implicit flow. If you need token expiration for security reasons, we strongly recommend that you use the authorization code flow instead.

Design guidelines

This section describes the design requirements and recommendations for the user screen that you host for OAuth linking flows. After it's called by Google's app, your platform displays a sign in to Google page and account linking consent screen to the user. The user is directed back to Google's app after giving their consent to link accounts.

This figure shows the steps for a user to link their Google account
            to your authentication system. The first screenshot shows
            user-initiated linking from your platform. The second image shows
            user sign-in to Google, while the third shows the user consent and
            confirmation for linking their Google account with your app. The
            final screenshot shows a successfully linked user account in the
            Google app.
Figure 1. Account linking user sign in to Google and consent screens.

Requirements

  1. You must communicate that the user’s account will be linked to Google, not a specific Google product like Google Home or Google Assistant.

Recommendations

We recommend that you do the following:

  1. Display Google's Privacy Policy. Include a link to Google’s Privacy Policy on the consent screen.

  2. Data to be shared. Use clear and concise language to tell the user what data of theirs Google requires and why.

  3. Clear call-to-action. State a clear call-to-action on your consent screen, such as “Agree and link.” This is because users need to understand what data they're required to share with Google to link their accounts.

  4. Ability to cancel. Provide a way for users to go back or cancel, if they choose not to link.

  5. Clear sign-in process. Ensure that users have clear method for signing in to their Google account, such as fields for their username and password or Sign in with Google.

  6. Ability to unlink. Offer a mechanism for users to unlink, such as a URL to their account settings on your platform. Alternatively, you can include a link to Google Account where users can manage their linked account.

  7. Ability to change user account. Suggest a method for users to switch their account(s). This is especially beneficial if users tend to have multiple accounts.

    • If a user must close the consent screen to switch accounts, send a recoverable error to Google so the user can sign in to the desired account with OAuth linking and the implicit flow.
  8. Include your logo. Display your company logo on the consent screen. Use your style guidelines to place your logo. If you wish to also display Google's logo, see Logos and trademarks.

Create the project

To create your project to use account linking:

  1. Go to the Google API Console.
  2. 프로젝트 생성을 클릭 하십시오 .
  3. 이름을 입력하거나 생성 된 제안을 수락하십시오.
  4. 나머지 필드를 확인하거나 편집하십시오.
  5. 작성을 클릭 하십시오 .

프로젝트 ID를 보려면

  1. Go to the Google API Console.
  2. 방문 페이지의 표에서 프로젝트를 찾으십시오. 프로젝트 ID가 ID 열에 나타납니다.

The Google Account Linking process includes a consent screen which tells users the application requesting access to their data, what kind of data they are asking for and the terms that apply. You will need to configure your OAuth consent screen before generating a Google API client ID.

  1. Open the OAuth consent screen page of the Google APIs console.
  2. If prompted, select the project you just created.
  3. On the "OAuth consent screen" page, fill out the form and click the “Save” button.

    Application name: The name of the application asking for consent. The name should accurately reflect your application and be consistent with the application name users see elsewhere. The application name will be shown on the Account Linking consent screen.

    Application logo: An image on the consent screen that will help users recognize your app. The logo is shown on Account linking consent screen and on account settings

    Support email: For users to contact you with questions about their consent.

    Scopes for Google APIs: Scopes allow your application to access your user's private Google data. For the Google Account Linking use case, default scope (email, profile, openid) is sufficient, you don’t need to add any sensitive scopes. It is generally a best practice to request scopes incrementally, at the time access is required, rather than up front. Learn more.

    Authorized domains: To protect you and your users, Google only allows applications that authenticate using OAuth to use Authorized Domains. Your applications' links must be hosted on Authorized Domains. Learn more.

    Application Homepage link: Home page for your application. Must be hosted on an Authorized Domain.

    Application Privacy Policy link: Shown on Google Account Linking consent screen. Must be hosted on an Authorized Domain.

    Application Terms of Service link (Optional): Must be hosted on an Authorized Domain.

    Figure 1. Google Account Linking Consent Screen for a fictitious Application, Tunery

  4. Check "Verification Status", if your application needs verification then click the "Submit For Verification" button to submit your application for verification. Refer to OAuth verification requirements for details.

OAuth 서버 구현

의 OAuth 2.0 암시 적 흐름을 지원하기 위해, 서비스는 HTTPS하여 사용할 권한 엔드 포인트를합니다. 이 끝점은 인증을 담당하고 데이터 액세스에 대한 사용자의 동의를 얻습니다. 권한 부여 끝점은 아직 로그인하지 않은 사용자에게 로그인 UI를 제공하고 요청된 액세스에 대한 동의를 기록합니다.

Google 애플리케이션이 서비스의 승인된 API 중 하나를 호출해야 하는 경우 Google은 이 엔드포인트를 사용하여 사용자를 대신하여 이러한 API를 호출할 수 있는 권한을 사용자로부터 얻습니다.

Google에서 시작한 일반적인 OAuth 2.0 암시적 흐름 세션에는 다음 흐름이 있습니다.

  1. Google은 사용자의 브라우저에서 인증 엔드포인트를 엽니다. 사용자가 아직 로그인하지 않은 경우 로그인하고, 아직 권한을 부여하지 않은 경우 Google에 API로 데이터에 액세스할 수 있는 권한을 부여합니다.
  2. 귀하의 서비스는 구글에 대한 토큰 액세스 및 수익을 만듭니다. 이렇게 하려면 요청에 첨부된 액세스 토큰을 사용하여 사용자의 브라우저를 다시 Google로 리디렉션합니다.
  3. Google은 서비스의 API를 호출하고 각 요청에 액세스 토큰을 첨부합니다. 서비스에서 액세스 토큰이 Google에 API 액세스 권한을 부여하는지 확인한 다음 API 호출을 완료합니다.

승인 요청 처리

Google 애플리케이션이 OAuth 2.0 암시적 흐름을 통해 계정 연결을 수행해야 하는 경우 Google은 다음 매개변수가 포함된 요청과 함께 사용자를 승인 엔드포인트로 보냅니다.

권한 부여 엔드포인트 매개변수
client_id Google에 할당한 클라이언트 ID입니다.
redirect_uri 이 요청에 대한 응답을 보내는 URL입니다.
state 리디렉션 URI에서 변경되지 않고 Google에 다시 전달되는 부기 값입니다.
response_type 응답에서 반환할 값의 유형입니다. 의 OAuth 2.0 암시 적 흐름에 대한 응답 유형은 항상 token .
user_locale 의 Google 계정 언어 설정 RFC5646의 형식은 사용자가 선호하는 언어로 콘텐츠를 현지화하는 데 사용됩니다.

권한 부여 엔드 포인트에서 사용할 수있는 경우 예를 들어, https://myservice.example.com/auth , 요청은 다음과 같습니다

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

승인 엔드포인트가 로그인 요청을 처리하도록 하려면 다음 단계를 수행하십시오.

  1. 검증 client_idredirect_uri 의도하지 않은 또는 잘못 클라이언트 애플리케이션에 대한 액세스 권한을 부여 방지하기 위해 값 :

    • 을 확인하는 것이 client_id Google에 할당 된 클라이언트 ID를 일치합니다.
    • URL에 의해 지정된 것을 확인 redirect_uri 매개 변수는 다음과 같은 형식이 있습니다
      https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID
      https://oauth-redirect-sandbox.googleusercontent.com/r/YOUR_PROJECT_ID
      
  2. 사용자가 서비스에 로그인되어 있는지 확인합니다. 사용자가 로그인하지 않은 경우 서비스의 로그인 또는 가입 절차를 완료합니다.

  3. Google에서 API에 액세스하는 데 사용할 액세스 토큰을 생성합니다. 액세스 토큰은 임의의 문자열 값이 될 수 있지만 사용자를 고유하게 나타내야 하며 토큰은 클라이언트를 위한 것이며 추측할 수 없어야 합니다.

  4. 에 의해 지정된 URL로 사용자의 브라우저를 리디렉션 HTTP 응답 보내기 redirect_uri 매개 변수를. URL 조각에 다음 매개변수를 모두 포함합니다.

    • access_token : 당신이 액세스 토큰은 생성
    • token_type : 문자열 bearer
    • state : 원래 요청에서 수정되지 않은 상태 값

    다음은 결과 URL의 예는 다음과 같습니다

    https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID#access_token=ACCESS_TOKEN&token_type=bearer&state=STATE_STRING

구글의 OAuth 2.0 리디렉션 핸들러는 것을 토큰 액세스 및 확인한다 수신 state 값이 변경되지 않았습니다. Google에서 서비스에 대한 액세스 토큰을 얻은 후 서비스 API에 대한 후속 호출에 토큰을 연결합니다.

사용자 정보 요청 처리

사용자 정보 엔드 포인트는 의 OAuth 2.0 보호 자원입니다 링크 된 사용자에 대한 반환 청구가. 다음 사용 사례를 제외하고 userinfo 끝점을 구현하고 호스팅하는 것은 선택 사항입니다.

토큰 엔드포인트에서 액세스 토큰이 성공적으로 검색되면 Google은 연결된 사용자에 대한 기본 프로필 정보를 검색하기 위해 userinfo 엔드포인트에 요청을 보냅니다.

userinfo 엔드포인트 요청 헤더
Authorization header Bearer 유형의 액세스 토큰입니다.

예를 들어, 사용자 정보 엔드 포인트에서 사용할 수있는 경우 https://myservice.example.com/userinfo , 요청은 다음과 같습니다

GET /userinfo HTTP/1.1
Host: myservice.example.com
Authorization: Bearer ACCESS_TOKEN

userinfo 엔드포인트가 요청을 처리하도록 하려면 다음 단계를 수행하십시오.

  1. Authorization 헤더에서 액세스 토큰을 추출하고 액세스 토큰과 연결된 사용자에 대한 정보를 반환합니다.
  2. 액세스 토큰이 유효하지 않은 경우, 사용을 가진 HTTP 401 권한 오류를 반환 WWW-Authenticate 응답 헤더. 다음은 사용자 정보 오류 응답의 예는 다음과
    HTTP/1.1 401 Unauthorized
    WWW-Authenticate: error="invalid_token",
    error_description="The Access Token expired"
    
    무단 또는 다른 실패 오류 응답이 연결 과정에서 리턴된다 (401), 오류가 복구 불가능한 될 경우, 검색된 토큰이 폐기되며 사용자가있을 것이다 연결 프로세스를 다시 시작합니다.
  3. 액세스 토큰이 유효, 반환 및 HTTPS 응답의 본문에 다음과 같은 JSON 객체와 HTTP 200 응답의 경우 :

    {
    "sub": "USER_UUID",
    "email": "EMAIL_ADDRESS",
    "given_name": "FIRST_NAME",
    "family_name": "LAST_NAME",
    "name": "FULL_NAME",
    "picture": "PROFILE_PICTURE",
    }
    
    당신의 사용자 정보 엔드 포인트가 다시 표시 HTTP 200 성공 응답하는 경우는, 토큰 검색 및 청구은 사용자의 Google에 등록 계정.

    사용자 정보 끝점 응답
    sub 시스템에서 사용자를 식별하는 고유 ID입니다.
    email 사용자의 이메일 주소입니다.
    given_name 옵션 : 사용자의 성.
    family_name 옵션 : 사용자의 성.
    name 옵션 : 사용자의 전체 이름입니다.
    picture 옵션 : 사용자의 프로필 사진.

구현 확인

You can validate your implementation by using the OAuth 2.0 Playground tool.

In the tool, do the following steps:

  1. Click Configuration to open the OAuth 2.0 Configuration window.
  2. In the OAuth flow field, select Client-side.
  3. In the OAuth Endpoints field, select Custom.
  4. Specify your OAuth 2.0 endpoint and the client ID you assigned to Google in the corresponding fields.
  5. In the Step 1 section, don't select any Google scopes. Instead, leave this field blank or type a scope valid for your server (or an arbitrary string if you don't use OAuth scopes). When you're done, click Authorize APIs.
  6. In the Step 2 and Step 3 sections, go through the OAuth 2.0 flow and verify that each step works as intended.

You can validate your implementation by using the Google Account Linking Demo tool.

In the tool, do the following steps:

  1. Click the Sign-in with Google button.
  2. Choose the account you'd like to link.
  3. Enter the service ID.
  4. Optionally enter one or more scopes that you will request access for.
  5. Click Start Demo.
  6. When prompted, confirm that you may consent and deny the linking request.
  7. Confirm that you are redirected to your platform.