# Using OAuth 2.0 for Web Server Applications[🔗](https://developers.google.com/identity/protocols/oauth2/web-server "將 OAuth 2.0 用於 Web 服務器應用程序")
[TOC]
###### tags: `oauth` `google`
---
Google API Client Library for Java:[Easily access Google APIs from Java](https://developers.google.com/api-client-library/java "Java 語言客戶端庫")
## Prerequisites<SUP>(先決條件)</SUP>
Any application that calls Google APIs needs to enable those APIs in the API Console.
### Enable APIs for your project<SUP>(為項目啟用 API)</SUP>
1. Open the API Library in Google API Console.

2. 選擇或建立一個新的項目。
3. 選擇要啟用的 API,然後單擊**啟用**按鈕。
### 創建授權憑證
1. Go to the Credentials page.

2. 單擊 **CREATE CREDENTIALS** 再單擊 **OAuth client ID**。

3. **Application type** 選擇 **Web application**。

填寫表格,使用 Java、PHP 等語言和框架的應用程序必須指定 **Authorized redirect URIs**。對於測試,可指定引用本地計算機的 URI,例如`http://localhost:8080`。
### 確定訪問範圍
[OAuth 2.0 Scopes for Google APIs](https://developers.google.com/identity/protocols/oauth2/scopes) 包含可用於訪問 Google API 的 scopes 的完整列表。
## 獲取 OAuth 2.0 訪問令牌
與 Google 的 OAuth 2.0 服務器交互以獲取用戶的同意以代表用戶執行 API 請求。應用程序必須先獲得該同意,然後才能執行需要用戶授權的 Google API 請求。
### 第 1 步:設置授權參數[🔗](https://developers.google.com/identity/protocols/oauth2/web-server#creatingclient)
創建授權請求。該請求設置了標識您的應用程序並定義用戶將被要求授予您的應用程序的權限的參數。
* 如果使用 Google 客戶端庫進行 OAuth 2.0 身份驗證和授權,則需要創建和配置定義這些參數的對象。
* 如果直接調用 Google OAuth 2.0 端點,您將生成一個 URL 並在該 URL 上設置參數。
```
```
### 第 2 步:重定向到 Google 的 OAuth 2.0 服務器
生成一個 URL 以從 Google 的 OAuth 2.0 服務器請求訪問:
```
```
將用戶重定向到`$auth_url`:
```
```
### 第 3 步:Google 提示用戶同意
將用戶重定向到 Google 的 OAuth 2.0 服務器以啟動身份驗證和授權過程。通常,當應用程序首先需要訪問用戶的數據時,就會發生這種情況。在增量授權的情況下,當應用程序首先需要訪問它尚無訪問權限的其他資源時,也會發生此步驟。
1. 生成一個 URL 以從 Google 的 OAuth 2.0 服務器請求訪問:
```
```
2. 將用戶重定向到`$auth_url`:
```
```
Google 會顯示一個同意窗口,其中顯示您的應用程序的名稱以及它請求使用用戶授權憑據訪問的 Google API 服務以及要授予的訪問權限範圍的摘要。然後,用戶可以同意授予對您的應用程序請求的一個或多個範圍的訪問權限或拒絕該請求。
下面列出了對 Google 的 OAuth 2.0 授權端點的請求常見的錯誤代碼和建議的解決方法。
* `admin_policy_enforced`
由於 Google Workspace 管理員的政策,Google 帳戶無法授權一個或多個請求的範圍。
* `disallowed_useragent`
授權端點顯示在 Google 的OAuth 2.0 政策不允許的嵌入式用戶代理中。
* `org_internal`
請求中的 OAuth 客戶端 ID 是限制對特定Google Cloud Organization 中的Google 帳戶的訪問的項目的一部分。
* `redirect_uri_mismatch`
該 redirect_uri 在授權請求傳遞不匹配的 OAuth 用戶端 ID 被授權的重定向 URI。
### 步驟 4:處理 OAuth 2.0 服務器響應
如果用戶批准訪問請求,則響應包含授權代碼。如果用戶不批准請求,則響應包含錯誤消息。返回給Web服務器的授權碼或錯誤信息出現在查詢字符串中:
* 錯誤響應
```
https://oauth2.example.com/auth?error=access_denied
```
* 授權碼響應
```
https://oauth2.example.com/auth?code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7
```
### 步驟 5:交换刷新和访问令牌的授权代码
To exchange an authorization code for an access token, use the authenticate method:
```
$client->authenticate($_GET['code']);
```
You can retrieve the access token with the getAccessToken method:
```
$access_token = $client->getAccessToken();
```
## Calling Google APIs
1. If you need to apply an access token to a new Google_Client object—for example, if you stored the access token in a user session—use the setAccessToken method.
```
$client->setAccessToken($access_token);
```
2. Build a service object for the API that you want to call. You build a service object by providing an authorized Google_Client object to the constructor for the API you want to call.
```
$drive = new Google_Service_Drive($client);
```
3. Make requests to the API service using the interface provided by the service object .
```
$files = $drive->files->listFiles(array())->getItems();
```
## Refreshing an access token (offline access)
Access tokens periodically expire and become invalid credentials for a related API request. You can refresh an access token without prompting the user for permission (including when the user is not present) if you requested offline access to the scopes associated with the token.
* If you use a Google API Client Library, the client object refreshes the access token as needed as long as you configure that object for offline access.
* If you are not using a client library, you need to set the access_type HTTP query parameter to offline when redirecting the user to Google's OAuth 2.0 server . In that case, Google's authorization server returns a refresh token when you exchange an authorization code for an access token. Then, if the access token expires (or at any other time), you can use a refresh token to obtain a new access token.
Requesting offline access is a requirement for any application that needs to access a Google API when the user is not present.
Server-side web applications, installed applications, and devices all obtain refresh tokens during the authorization process.
If your application needs offline access to a Google API, set the API client's access type to offline:
```
$client->setAccessType("offline");
```
After a user grants offline access to the requested scopes, you can continue to use the API client to access Google APIs on the user's behalf when the user is offline. The client object will refresh the access token as needed.