這是 Classroom 外掛程式的第二秒逐步操作說明 這一系列的影片
在這個逐步操作說明中,您會將 Google 登入功能新增至網頁應用程式。這是 必要的行為。使用 這項授權流程適用於所有日後對 API 的呼叫。
在本逐步操作說明中,您將完成下列步驟:
- 設定網頁應用程式,在 iframe 內維護工作階段資料。
- 實作 Google OAuth 2.0 伺服器對伺服器登入流程。
- 發出對 OAuth 2.0 API 的呼叫。
- 建立其他路徑,支援授權、登出及測試 以及 API 呼叫
完成後,您就可以在網頁應用程式內完全授權使用者,並向 Google API
瞭解授權流程
Google API 使用 OAuth 2.0 通訊協定進行驗證及授權。 如需 Google OAuth 實作的完整說明,請參閱 Google Identity OAuth 指南。
應用程式憑證是在 Google Cloud 中管理。導入這些指令後 請實作四個步驟流程,以便驗證並授權 使用者:
- 要求授權。請在這項要求中提供回呼網址。 完成後,您會收到授權網址。
- 將使用者重新導向至授權網址。產生的頁面會通知 並提示他們允許存取。 完成後,系統會將使用者轉送至回呼網址。
- 透過回呼路徑接收授權碼。交換 存取權杖和更新權杖的授權碼。
- 使用權杖呼叫 Google API。
取得 OAuth 2.0 憑證
確認您已建立並下載 OAuth 憑證,方法如: 「總覽」頁面您的專案必須使用這些憑證才能登入使用者。
實作授權流程
將邏輯和路徑新增至網頁應用程式,以實現上述流程,包括 這些功能:
- 抵達到達網頁後,啟動授權流程。
- 要求授權並處理授權伺服器回應。
- 清除已儲存的憑證。
- 撤銷應用程式的權限。
- 測試 API 呼叫。
開始授權
如有需要,請修改到達網頁以啟動授權流程。 外掛程式可能有兩種狀態未儲存任何符記 ,或您需要從 OAuth 2.0 伺服器取得權杖。執行 測試 API 呼叫 (如果工作階段有符記的話),或提示使用者 登入。
Python
開啟 routes.py
檔案。首先,建立一些常數和 Cookie
請務必根據 iframe 安全性建議進行設定。
# The file that contains the OAuth 2.0 client_id and client_secret.
CLIENT_SECRETS_FILE = "client_secret.json"
# The OAuth 2.0 access scopes to request.
# These scopes must match the scopes in your Google Cloud project's OAuth Consent
# Screen: https://console.cloud.google.com/apis/credentials/consent
SCOPES = [
"openid",
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/classroom.addons.teacher",
"https://www.googleapis.com/auth/classroom.addons.student"
]
# Flask cookie configurations.
app.config.update(
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="None",
)
移至外掛程式到達路徑 (本例中為 /classroom-addon
檔案)。新增邏輯,在工作階段「不包含」時顯示登入頁面
「憑證」鍵。
@app.route("/classroom-addon")
def classroom_addon():
if "credentials" not in flask.session:
return flask.render_template("authorization.html")
return flask.render_template(
"addon-discovery.html",
message="You've reached the addon discovery page.")
Java
本逐步操作說明的程式碼位於 step_02_sign_in
模組中。
開啟 application.properties
檔案,然後新增會符合以下條件的工作階段設定:
請遵循 iframe 安全性建議。
# iFrame security recommendations call for cookies to have the HttpOnly and
# secure attribute set
server.servlet.session.cookie.http-only=true
server.servlet.session.cookie.secure=true
# Ensures that the session is maintained across the iframe and sign-in pop-up.
server.servlet.session.cookie.same-site=none
建立服務類別 (step_02_sign_in
模組中的 AuthService.java
)
處理控制器檔案中端點背後的邏輯並進行設定
重新導向 URI、用戶端密鑰檔案位置和您外掛程式的範圍
而負責任的 AI 技術做法
有助於達成這項目標重新導向 URI 的用途是將使用者重新轉送至特定 URI
並在對方授權您的應用程式後顯示詳情請參閱
原始碼中的 README.md
,以便瞭解放置
client_secret.json
檔案。
@Service
public class AuthService {
private static final String REDIRECT_URI = "https://localhost:5000/callback";
private static final String CLIENT_SECRET_FILE = "client_secret.json";
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static final String[] REQUIRED_SCOPES = {
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/classroom.addons.teacher",
"https://www.googleapis.com/auth/classroom.addons.student"
};
/** Creates and returns a Collection object with all requested scopes.
* @return Collection of scopes requested by the application.
*/
public static Collection<String> getScopes() {
return new ArrayList<>(Arrays.asList(REQUIRED_SCOPES));
}
}
開啟控制器檔案 (位於 step_02_sign_in
中的 AuthController.java
)
模組),並在到達路徑中加入邏輯,在發生
工作階段「不含」credentials
鍵。
@GetMapping(value = {"/start-auth-flow"})
public String startAuthFlow(Model model) {
try {
return "authorization";
} catch (Exception e) {
return onError(e.getMessage(), model);
}
}
@GetMapping(value = {"/addon-discovery"})
public String addon_discovery(HttpSession session, Model model) {
try {
if (session == null || session.getAttribute("credentials") == null) {
return startAuthFlow(model);
}
return "addon-discovery";
} catch (Exception e) {
return onError(e.getMessage(), model);
}
}
您的授權頁面應包含讓使用者「簽署」的連結或按鈕
。使用者點選這個選項後,應會重新導向至 authorize
路徑。
要求授權
如要提出授權要求,建構使用者並將其重新導向至驗證頁面 網址。這個網址包含多項資訊,例如範圍 「之後」授權的目的地路徑,以及網頁應用程式的 用戶端 ID。您可以在這個授權網址範例中查看這些授權。
Python
將以下匯入項目新增至 routes.py
檔案。
import google_auth_oauthlib.flow
建立新路徑 /authorize
。建立以下項目的執行個體:
google_auth_oauthlib.flow.Flow
;我們強烈建議您使用
請使用 from_client_secrets_file
方法執行此操作。
@app.route("/authorize")
def authorize():
# Create flow instance to manage the OAuth 2.0 Authorization Grant Flow
# steps.
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
CLIENT_SECRETS_FILE, scopes=SCOPES)
設定 flow
的 redirect_uri
;也就是你希望使用者
授權應用程式後才會傳回 。這是下列類別的/callback
範例。
# The URI created here must exactly match one of the authorized redirect
# URIs for the OAuth 2.0 client, which you configured in the API Console. If
# this value doesn't match an authorized URI, you will get a
# "redirect_uri_mismatch" error.
flow.redirect_uri = flask.url_for("callback", _external=True)
使用流程物件建構 authorization_url
和 state
。商店
工作階段中的 state
;用於驗證預測結果的真實性
伺服器回應。最後,請將使用者重新導向至
authorization_url
。
authorization_url, state = flow.authorization_url(
# Enable offline access so that you can refresh an access token without
# re-prompting the user for permission. Recommended for web server apps.
access_type="offline",
# Enable incremental authorization. Recommended as a best practice.
include_granted_scopes="true")
# Store the state so the callback can verify the auth server response.
flask.session["state"] = state
# Redirect the user to the OAuth authorization URL.
return flask.redirect(authorization_url)
Java
在 AuthService.java
檔案中加入以下方法,將
,然後用它來擷取授權網址:
getClientSecrets()
方法會讀取用戶端密鑰檔案並建構GoogleClientSecrets
物件。getFlow()
方法會建立GoogleAuthorizationCodeFlow
的例項。authorize()
方法會使用GoogleAuthorizationCodeFlow
物件,state
參數,以及用來擷取授權網址的重新導向 URI。state
參數是用來驗證回應的真實性 授權伺服器存取。接著, 方法會傳回含 授權網址和state
參數。
/** Reads the client secret file downloaded from Google Cloud.
* @return GoogleClientSecrets read in from client secret file. */
public GoogleClientSecrets getClientSecrets() throws Exception {
try {
InputStream in = SignInApplication.class.getClassLoader()
.getResourceAsStream(CLIENT_SECRET_FILE);
if (in == null) {
throw new FileNotFoundException("Client secret file not found: "
+ CLIENT_SECRET_FILE);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets
.load(JSON_FACTORY, new InputStreamReader(in));
return clientSecrets;
} catch (Exception e) {
throw e;
}
}
/** Builds and returns authorization code flow.
* @return GoogleAuthorizationCodeFlow object used to retrieve an access
* token and refresh token for the application.
* @throws Exception if reading client secrets or building code flow object
* is unsuccessful.
*/
public GoogleAuthorizationCodeFlow getFlow() throws Exception {
try {
GoogleAuthorizationCodeFlow authorizationCodeFlow =
new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT,
JSON_FACTORY,
getClientSecrets(),
getScopes())
.setAccessType("offline")
.build();
return authorizationCodeFlow;
} catch (Exception e) {
throw e;
}
}
/** Builds and returns a map with the authorization URL, which allows the
* user to give the app permission to their account, and the state parameter,
* which is used to prevent cross site request forgery.
* @return map with authorization URL and state parameter.
* @throws Exception if building the authorization URL is unsuccessful.
*/
public HashMap authorize() throws Exception {
HashMap<String, String> authDataMap = new HashMap<>();
try {
String state = new BigInteger(130, new SecureRandom()).toString(32);
authDataMap.put("state", state);
GoogleAuthorizationCodeFlow flow = getFlow();
String authUrl = flow
.newAuthorizationUrl()
.setState(state)
.setRedirectUri(REDIRECT_URI)
.build();
String url = authUrl;
authDataMap.put("url", url);
return authDataMap;
} catch (Exception e) {
throw e;
}
}
使用建構函式插入功能,在 控制器類別
/** Declare AuthService to be used in the Controller class constructor. */
private final AuthService authService;
/** AuthController constructor. Uses constructor injection to instantiate
* the AuthService and UserRepository classes.
* @param authService the service class that handles the implementation logic
* of requests.
*/
public AuthController(AuthService authService) {
this.authService = authService;
}
將 /authorize
端點新增至控制器類別。這個端點呼叫
使用 AuthService authorize()
方法擷取 state
參數
和授權網址接著,端點會儲存 state
參數,並將使用者重新導向至授權網址。
/** Redirects the sign-in pop-up to the authorization URL.
* @param response the current response to pass information to.
* @param session the current session.
* @throws Exception if redirection to the authorization URL is unsuccessful.
*/
@GetMapping(value = {"/authorize"})
public void authorize(HttpServletResponse response, HttpSession session)
throws Exception {
try {
HashMap authDataMap = authService.authorize();
String authUrl = authDataMap.get("url").toString();
String state = authDataMap.get("state").toString();
session.setAttribute("state", state);
response.sendRedirect(authUrl);
} catch (Exception e) {
throw e;
}
}
處理伺服器回應
授權後,使用者會從redirect_uri
上一個步驟在上述範例中,這條路徑為 /callback
。
當使用者從code
授權頁面。接著使用程式碼交換存取權並更新權杖:
Python
將以下匯入項目新增至 Flask 伺服器檔案。
import google.oauth2.credentials
import googleapiclient.discovery
將路徑新增至伺服器。建構另一個
google_auth_oauthlib.flow.Flow
,但這次會重複使用
上一個步驟
@app.route("/callback")
def callback():
state = flask.session["state"]
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
flow.redirect_uri = flask.url_for("callback", _external=True)
接著,要求存取權並更新權杖。幸好,flow
物件也
包含可完成這項操作的 fetch_token
方法。這個方法
code
或 authorization_response
引數。使用
authorization_response
,因為這是要求中的完整網址。
authorization_response = flask.request.url
flow.fetch_token(authorization_response=authorization_response)
您現已擁有完整的憑證!將圖片儲存在工作階段中, 可透過其他方法或路徑擷取,再重新導向至外掛程式 到達網頁
credentials = flow.credentials
flask.session["credentials"] = {
"token": credentials.token,
"refresh_token": credentials.refresh_token,
"token_uri": credentials.token_uri,
"client_id": credentials.client_id,
"client_secret": credentials.client_secret,
"scopes": credentials.scopes
}
# Close the pop-up by rendering an HTML page with a script that redirects
# the owner and closes itself. This can be done with a bit of JavaScript:
# <script>
# window.opener.location.href = "{{ url_for('classroom_addon') }}";
# window.close();
# </script>
return flask.render_template("close-me.html")
Java
新增方法至您的服務類別,以透過下列方式傳回 Credentials
物件
執行從 的重新導向擷取到的
授權網址這個 Credentials
物件稍後用於擷取
存取權杖並更新
/** Returns the required credentials to access Google APIs.
* @param authorizationCode the authorization code provided by the
* authorization URL that's used to obtain credentials.
* @return the credentials that were retrieved from the authorization flow.
* @throws Exception if retrieving credentials is unsuccessful.
*/
public Credential getAndSaveCredentials(String authorizationCode) throws Exception {
try {
GoogleAuthorizationCodeFlow flow = getFlow();
GoogleClientSecrets googleClientSecrets = getClientSecrets();
TokenResponse tokenResponse = flow.newTokenRequest(authorizationCode)
.setClientAuthentication(new ClientParametersAuthentication(
googleClientSecrets.getWeb().getClientId(),
googleClientSecrets.getWeb().getClientSecret()))
.setRedirectUri(REDIRECT_URI)
.execute();
Credential credential = flow.createAndStoreCredential(tokenResponse, null);
return credential;
} catch (Exception e) {
throw e;
}
}
為重新導向 URI 新增端點至控制器。擷取
授權碼和 state
參數。比較
state
參數設為儲存在工作階段中的 state
屬性。如果他們
配對,然後繼續進行授權流程。如果兩者不相符
傳回錯誤。
然後,呼叫 AuthService
getAndSaveCredentials
方法並傳入
驗證程式碼擷取 Credentials
之後
物件,請將其儲存在工作階段中。接著,請關閉對話方塊,並將
使用者前往外掛程式到達網頁
/** Handles the redirect URL to grant the application access to the user's
* account.
* @param request the current request used to obtain the authorization code
* and state parameter from.
* @param session the current session.
* @param response the current response to pass information to.
* @param model the Model interface to pass error information that's
* displayed on the error page.
* @return the close-pop-up template if authorization is successful, or the
* onError method to handle and display the error message.
*/
@GetMapping(value = {"/callback"})
public String callback(HttpServletRequest request, HttpSession session,
HttpServletResponse response, Model model) {
try {
String authCode = request.getParameter("code");
String requestState = request.getParameter("state");
String sessionState = session.getAttribute("state").toString();
if (!requestState.equals(sessionState)) {
response.setStatus(401);
return onError("Invalid state parameter.", model);
}
Credential credentials = authService.getAndSaveCredentials(authCode);
session.setAttribute("credentials", credentials);
return "close-pop-up";
} catch (Exception e) {
return onError(e.getMessage(), model);
}
}
測試 API 呼叫
流程完成之後,您現在可以向 Google API 發出呼叫!
舉例來說,您可以要求取得使用者的個人資料。您可以要求 透過 OAuth 2.0 API 擷取使用者資訊
Python
請參閱 OAuth 2.0 探索 API 用來取得填入的 UserInfo 物件。
# Retrieve the credentials from the session data and construct a
# Credentials instance.
credentials = google.oauth2.credentials.Credentials(
**flask.session["credentials"])
# Construct the OAuth 2.0 v2 discovery API library.
user_info_service = googleapiclient.discovery.build(
serviceName="oauth2", version="v2", credentials=credentials)
# Request and store the username in the session.
# This allows it to be used in other methods or in an HTML template.
flask.session["username"] = (
user_info_service.userinfo().get().execute().get("name"))
Java
使用下列指令,在建構 UserInfo
物件的服務類別中建立方法
Credentials
做為參數。
/** Obtains the Userinfo object by passing in the required credentials.
* @param credentials retrieved from the authorization flow.
* @return the Userinfo object for the currently signed-in user.
* @throws IOException if creating UserInfo service or obtaining the
* Userinfo object is unsuccessful.
*/
public Userinfo getUserInfo(Credential credentials) throws IOException {
try {
Oauth2 userInfoService = new Oauth2.Builder(
new NetHttpTransport(),
new GsonFactory(),
credentials).build();
Userinfo userinfo = userInfoService.userinfo().get().execute();
return userinfo;
} catch (Exception e) {
throw e;
}
}
將 /test
端點新增至顯示使用者電子郵件的控制器。
/** Returns the test request page with the user's email.
* @param session the current session.
* @param model the Model interface to pass error information that's
* displayed on the error page.
* @return the test page that displays the current user's email or the
* onError method to handle and display the error message.
*/
@GetMapping(value = {"/test"})
public String test(HttpSession session, Model model) {
try {
Credential credentials = (Credential) session.getAttribute("credentials");
Userinfo userInfo = authService.getUserInfo(credentials);
String userInfoEmail = userInfo.getEmail();
if (userInfoEmail != null) {
model.addAttribute("userEmail", userInfoEmail);
} else {
return onError("Could not get user email.", model);
}
return "test";
} catch (Exception e) {
return onError(e.getMessage(), model);
}
}
清除憑證
你可以「清除」使用者的憑證,方法是從目前工作階段移除使用者。 即可在外掛程式到達網頁上測試轉送。
建議您顯示使用者已登出 將消費者重新導向至外掛程式到達網頁您的應用程式應完成 驗證流程以取得新憑證,但系統不會提示使用者 重新授權應用程式。
Python
@app.route("/clear")
def clear_credentials():
if "credentials" in flask.session:
del flask.session["credentials"]
del flask.session["username"]
return flask.render_template("signed-out.html")
您也可以使用 flask.session.clear()
,但這可能不是預期的情況
如果有其他值儲存在這個工作階段中。
Java
在控制器中新增 /clear
端點。
/** Clears the credentials in the session and returns the sign-out
* confirmation page.
* @param session the current session.
* @return the sign-out confirmation page.
*/
@GetMapping(value = {"/clear"})
public String clear(HttpSession session) {
try {
if (session != null && session.getAttribute("credentials") != null) {
session.removeAttribute("credentials");
}
return "sign-out";
} catch (Exception e) {
return onError(e.getMessage(), model);
}
}
撤銷應用程式的權限
使用者只要傳送 POST
要求,即可撤銷應用程式的權限
https://oauth2.googleapis.com/revoke
。要求應包含使用者的
存取權杖
Python
import requests
@app.route("/revoke")
def revoke():
if "credentials" not in flask.session:
return flask.render_template("addon-discovery.html",
message="You need to authorize before " +
"attempting to revoke credentials.")
credentials = google.oauth2.credentials.Credentials(
**flask.session["credentials"])
revoke = requests.post(
"https://oauth2.googleapis.com/revoke",
params={"token": credentials.token},
headers={"content-type": "application/x-www-form-urlencoded"})
if "credentials" in flask.session:
del flask.session["credentials"]
del flask.session["username"]
status_code = getattr(revoke, "status_code")
if status_code == 200:
return flask.render_template("authorization.html")
else:
return flask.render_template(
"index.html", message="An error occurred during revocation!")
Java
新增方法至服務類別,以呼叫撤銷端點。
/** Revokes the app's permissions to the user's account.
* @param credentials retrieved from the authorization flow.
* @return response entity returned from the HTTP call to obtain response
* information.
* @throws RestClientException if the POST request to the revoke endpoint is
* unsuccessful.
*/
public ResponseEntity<String> revokeCredentials(Credential credentials) throws RestClientException {
try {
String accessToken = credentials.getAccessToken();
String url = "https://oauth2.googleapis.com/revoke?token=" + accessToken;
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
HttpEntity<Object> httpEntity = new HttpEntity<Object>(httpHeaders);
ResponseEntity<String> responseEntity = new RestTemplate().exchange(
url,
HttpMethod.POST,
httpEntity,
String.class);
return responseEntity;
} catch (RestClientException e) {
throw e;
}
}
在控制器中新增端點 /revoke
,用於清除工作階段
如果使用者撤銷了授權,則將使用者重新導向至授權網頁
成功。
/** Revokes the app's permissions and returns the authorization page.
* @param session the current session.
* @return the authorization page.
* @throws Exception if revoking access is unsuccessful.
*/
@GetMapping(value = {"/revoke"})
public String revoke(HttpSession session) throws Exception {
try {
if (session != null && session.getAttribute("credentials") != null) {
Credential credentials = (Credential) session.getAttribute("credentials");
ResponseEntity responseEntity = authService.revokeCredentials(credentials);
Integer httpStatusCode = responseEntity.getStatusCodeValue();
if (httpStatusCode != 200) {
return onError("There was an issue revoking access: " +
responseEntity.getStatusCode(), model);
}
session.removeAttribute("credentials");
}
return startAuthFlow(model);
} catch (Exception e) {
return onError(e.getMessage(), model);
}
}
測試外掛程式
登入 Google Classroom 老師的測試使用者。前往「課堂作業」分頁,然後 建立新的作業。按一下文字區域下方的「Add-ons」按鈕。 然後選取加購方案iframe 會開啟,外掛程式也會載入 您在 GWM SDK 應用程式中指定的附件設定 URI 設定 頁面。
恭喜!您可以繼續進行下一個步驟:處理重複作業 外掛程式的造訪次數。