Common Using OAuth 2.0 to Access Google APIs

황제낙엽 2019.09.05 00:21 조회 수 : 3101

Google APIs use the OAuth 2.0 protocol for authentication and authorization. Google supports common OAuth 2.0 scenarios such as those for web server, installed, and client-side applications.

To begin, obtain OAuth 2.0 client credentials from the Google API Console. Then your client application requests an access token from the Google Authorization Server, extracts a token from the response, and sends the token to the Google API that you want to access. For an interactive demonstration of using OAuth 2.0 with Google (including the option to use your own client credentials), experiment with the OAuth 2.0 Playground.

This page gives an overview of the OAuth 2.0 authorization scenarios that Google supports, and provides links to more detailed content. For details about using OAuth 2.0 for authentication, see OpenID Connect.

Basic steps

All applications follow a basic pattern when accessing a Google API using OAuth 2.0. At a high level, you follow four steps:

1. Obtain OAuth 2.0 credentials from the Google API Console.

Visit the Google API Console to obtain OAuth 2.0 credentials such as a client ID and client secret that are known to both Google and your application. The set of values varies based on what type of application you are building. For example, a JavaScript application does not require a secret, but a web server application does.

2. Obtain an access token from the Google Authorization Server.

Before your application can access private data using a Google API, it must obtain an access token that grants access to that API. A single access token can grant varying degrees of access to multiple APIs. A variable parameter called scopecontrols the set of resources and operations that an access token permits. During the access-token request, your application sends one or more values in the scope parameter.

There are several ways to make this request, and they vary based on the type of application you are building. For example, a JavaScript application might request an access token using a browser redirect to Google, while an application installed on a device that has no browser uses web service requests.

Some requests require an authentication step where the user logs in with their Google account. After logging in, the user is asked whether they are willing to grant the permissions that your application is requesting. This process is called user consent.

If the user grants the permission, the Google Authorization Server sends your application an access token (or an authorization code that your application can use to obtain an access token). If the user does not grant the permission, the server returns an error.

It is generally a best practice to request scopes incrementally, at the time access is required, rather than up front. For example, an app that wants to support purchases should not request Google Wallet access until the user presses the “buy” button; see Incremental authorization.

3. Send the access token to an API.

After an application obtains an access token, it sends the token to a Google API in an HTTP authorization header. It is possible to send tokens as URI query-string parameters, but we don't recommend it, because URI parameters can end up in log files that are not completely secure. Also, it is good REST practice to avoid creating unnecessary URI parameter names.

Access tokens are valid only for the set of operations and resources described in the scope of the token request. For example, if an access token is issued for the Google+ API, it does not grant access to the Google Contacts API. You can, however, send that access token to the Google+ API multiple times for similar operations.

4. Refresh the access token, if necessary.

Access tokens have limited lifetimes. If your application needs access to a Google API beyond the lifetime of a single access token, it can obtain a refresh token. A refresh token allows your application to obtain new access tokens.

Scenarios

Web server applications

The Google OAuth 2.0 endpoint supports web server applications that use languages and frameworks such as PHP, Java, Python, Ruby, and ASP.NET.

The authorization sequence begins when your application redirects a browser to a Google URL; the URL includes query parameters that indicate the type of access being requested. Google handles the user authentication, session selection, and user consent. The result is an authorization code, which the application can exchange for an access token and a refresh token.

The application should store the refresh token for future use and use the access token to access a Google API. Once the access token expires, the application uses the refresh token to obtain a new one.

Your application sends a token request to the Google Authorization Server, receives an authorization code,
exchanges the code for a token, and uses the token to call a Google API endpoint.

For details, see Using OAuth 2.0 for Web Server Applications.

Installed applications

The Google OAuth 2.0 endpoint supports applications that are installed on devices such as computers, mobile devices, and tablets. When you create a client ID through the Google API Console, specify that this is an Installed application, then select Android, Chrome, iOS, or "Other" as the application type.

The process results in a client ID and, in some cases, a client secret, which you embed in the source code of your application. (In this context, the client secret is obviously not treated as a secret.)

The authorization sequence begins when your application redirects a browser to a Google URL; the URL includes query parameters that indicate the type of access being requested. Google handles the user authentication, session selection, and user consent. The result is an authorization code, which the application can exchange for an access token and a refresh token.

The application should store the refresh token for future use and use the access token to access a Google API. Once the access token expires, the application uses the refresh token to obtain a new one.

Your application sends a token request to the Google Authorization Server, receives an authorization code,
exchanges the code for a token, and uses the token to call a Google API endpoint.

For details, see Using OAuth 2.0 for Installed Applications.

Client-side (JavaScript) applications

The Google OAuth 2.0 endpoint supports JavaScript applications that run in a browser.

The authorization sequence begins when your application redirects a browser to a Google URL; the URL includes query parameters that indicate the type of access being requested. Google handles the user authentication, session selection, and user consent.

The result is an access token, which the client should validate before including it in a Google API request. When the token expires, the application repeats the process.

Your JS application sends a token request to the Google Authorization Server, receives a token,
validates the token, and uses the token to call a Google API endpoint.

For details, see Using OAuth 2.0 for Client-side Applications.

Applications on limited-input devices

The Google OAuth 2.0 endpoint supports applications that run on limited-input devices such as game consoles, video cameras, and printers.

The authorization sequence begins with the application making a web service request to a Google URL for an authorization code. The response contains several parameters, including a URL and a code that the application shows to the user.

The user obtains the URL and code from the device, then switches to a separate device or computer with richer input capabilities. The user launches a browser, navigates to the specified URL, logs in, and enters the code.

Meanwhile, the application polls a Google URL at a specified interval. After the user approves access, the response from the Google server contains an access token and refresh token. The application should store the refresh token for future use and use the access token to access a Google API. Once the access token expires, the application uses the refresh token to obtain a new one.

The user logs in on a separate device that has a browser.

For details, see Using OAuth 2.0 for Devices.

Service accounts

Google APIs such as the Prediction API and Google Cloud Storage can act on behalf of your application without accessing user information. In these situations your application needs to prove its own identity to the API, but no user consent is necessary. Similarly, in enterprise scenarios, your application can request delegated access to some resources.

For these types of server-to-server interactions you need a service account, which is an account that belongs to your application instead of to an individual end-user. Your application calls Google APIs on behalf of the service account, and user consent is not required. (In non-service-account scenarios, your application calls Google APIs on behalf of end-users, and user consent is sometimes required.)

A service account's credentials, which you obtain from the Google API Console, include a generated email address that is unique, a client ID, and at least one public/private key pair. You use the client ID and one private key to create a signed JWT and construct an access-token request in the appropriate format. Your application then sends the token request to the Google OAuth 2.0 Authorization Server, which returns an access token. The application uses the token to access a Google API. When the token expires, the application repeats the process.

Your server application uses a JWT to request a token from the Google Authorization Server,
then uses the token to call a Google API endpoint. No end-user is involved.

For details, see the service-account documentation.

Token size

Tokens can vary in size, up to the following limits:

  • Authorization codes: 256 bytes
  • Access tokens: 2048 bytes
  • Refresh tokens: 512 bytes

Google reserves the right to change token size within these limits, and your application must support variable token sizes accordingly.

Token expiration

You must write your code to anticipate the possibility that a granted refresh token might no longer work. A refresh token might stop working for one of these reasons:

  • The user has revoked your app's access.
  • The refresh token has not been used for six months.
  • The user changed passwords and the refresh token contains Gmail scopes.
  • The user account has exceeded a maximum number of granted (live) refresh tokens.

There is currently a limit of 50 refresh tokens per user account per client. If the limit is reached, creating a new refresh token automatically invalidates the oldest refresh token without warning. This limit does not apply to service accounts.

There is also a larger limit on the total number of refresh tokens a user account or service account can have across all clients. Most normal users won't exceed this limit but a developer's test account might.

If you need to authorize multiple programs, machines, or devices, one workaround is to limit the number of clients that you authorize per user account to 15 or 20. If you are a G Suite admin, you can create additional admin users and use them to authorize some of the clients.

Client libraries

The following client libraries integrate with popular frameworks, which makes implementing OAuth 2.0 simpler. More features will be added to the libraries over time.

번호 제목 글쓴이 날짜 조회 수
공지 Software Development Trend (with Java) 황제낙엽 2024.01.19 2912
154 페이스북에서 알게된 AI의 현주소 황제낙엽 2026.05.22 116
153 MIT License 의 AI Coding Agent - Opencode 황제낙엽 2026.01.23 176
152 개발자를 위한 바이브 코딩 추천 툴 7가지 황제낙엽 2025.12.07 192
151 현재 유행하는 AI 들을 이용하는 방법 황제낙엽 2025.01.31 1136
150 SAP GUI AI Agent를 생성했습니다. 황제낙엽 2025.01.12 592
149 프로그래밍에서 polling 의 의미 황제낙엽 2025.01.05 459
148 [Gemini] server 에서 client 의 function call 를 위한 방안과 특징 황제낙엽 2025.01.03 418
147 Gretty 와 Jetty 에 대하여 황제낙엽 2024.11.01 602
146 naver(네이버) developers에서 제공하는 OAuth REST API 관련 링크 황제낙엽 2023.12.31 452
145 (bing) 소프트웨어의 일반적인 버전 관리 규칙 황제낙엽 2023.10.24 456
144 kakao(카카오) developers에서 제공하는 OAuth REST API 관련 링크 황제낙엽 2023.10.22 506
143 식품(상품) 바코드를 조회하여 제품 정보 획득하기 file 황제낙엽 2023.08.07 1455
142 식약처(식품의약품안전처) 공공데이터 API 황제낙엽 2023.08.07 652
141 서비스 이용약관과 개인정보 처리방침 황제낙엽 2023.07.15 446
140 프로젝트 운영 관리 소프트웨어로 100% 자동화된 '데브옵스(DevOps)' 구축하기 (LG CNS) secret 황제낙엽 2023.07.12 65
139 개발자이기 전에 노동자로써의 삶에 대한 고찰 (지극히 개인적인 사설) 황제낙엽 2023.02.28 472
138 [SDC22 키노트 요약정리] 더 쉽게, 끊김 없이 매끄럽게! ‘캄 테크’ 향해 진화하는 미래의 집 황제낙엽 2022.12.24 501
137 변수 네이밍 표기법 종류 file 황제낙엽 2022.11.30 479
136 이미지에서 텍스트를 추출하는 OCR 방법들 file 황제낙엽 2022.09.23 566
135 지수(과학적 표기법, "E") 서식 지정자 (2) 황제낙엽 2021.07.06 495