這是 Classroom 外掛程式的第三分逐步操作說明 這一系列的影片
在本逐步操作說明中,系統會自動為您處理重複造訪的外掛程式 擷取使用者先前授予的憑證。接著,請將使用者轉送至 立即發出 API 要求的網頁。必填 以及 Classroom 外掛程式的行為。
在本逐步操作說明中,您將完成下列步驟:
- 為使用者憑證實作永久儲存空間。
- 擷取及評估
login_hint
外掛程式查詢參數。這是 已登入使用者的專屬 Google ID 號碼。
完成後,您就可以在網頁應用程式內完全授權使用者,並向 Google API
瞭解 iframe 查詢參數
Classroom 會在
正在打開Google Classroom
將數個 GET
查詢參數附加至 URI;這些包含實用的資訊
背景資訊。舉例來說,如果您的附件探索 URI 為
https://example.com/addon
,Classroom 會建立 iframe 中的以下欄位:
來源網址已設為
https://example.com/addon?courseId=XXX&itemId=YYY&itemType=courseWork&addOnToken=ZZZ
,
其中 XXX
、YYY
和 ZZZ
是字串 ID。請參閱 iframe 指南中的
此情境的詳細說明。
探索網址有五個可用的查詢參數:
courseId
:目前 Classroom 課程的 ID。itemId
:使用者正在編輯或建立的串流項目 ID。itemType
:使用者正在建立或編輯的串流項目類型,courseWork
、courseWorkMaterial
或announcement
。addOnToken
:用來授權特定人員的符記 Classroom 外掛程式動作。login_hint
:目前使用者的 Google ID。
這份逐步操作說明會介紹 login_hint
。系統會根據此設定
查詢參數,置入授權流程中 (如果遺失的話),或
外掛程式探索頁面 (如果有的話)。
存取查詢參數
查詢參數會透過 URI 字串傳遞至網頁應用程式。商店 在你工作階段中使用這些值如何在授權流程中執行 儲存及擷取使用者相關資訊。這些查詢參數 會在外掛程式首次開啟時傳遞
Python
前往 Flask 路徑的定義 (routes.py
,
啟用)。外掛程式登陸路線頂端
(目前提供的範例中為 /classroom-addon
),請擷取並儲存
login_hint
查詢參數:
# If the login_hint query parameter is available, we'll store it in the session.
if flask.request.args.get("login_hint"):
flask.session["login_hint"] = flask.request.args.get("login_hint")
確認 login_hint
(如有) 儲存在工作階段中。這是
儲存這些值;是暫時性的
。
# It's possible that we might return to this route later, in which case the
# parameters will not be passed in. Instead, use the values cached in the
# session.
login_hint = flask.session.get("login_hint")
# If there's still no login_hint query parameter, this must be their first
# time signing in, so send the user to the sign in page.
if login_hint is None:
return start_auth_flow()
Java
前往控制器類別中的外掛程式到達路徑
(提供範例的 AuthController.java
中有 /addon-discovery
)。在
在這個路線的起點,擷取並儲存 login_hint
查詢
參數。
/** Retrieve the login_hint query parameter from the request URL if present. */
String login_hint = request.getParameter("login_hint");
確認 login_hint
(如有) 儲存在工作階段中。這是
儲存這些值;是暫時性的
。
/** If login_hint wasn't sent, use the values in the session. */
if (login_hint == null) {
login_hint = (String) session.getAttribute("login_hint");
}
/** If the there is still no login_hint, route the user to the authorization
* page. */
if (login_hint == null) {
return startAuthFlow(model);
}
/** If the login_hint query parameter is provided, add it to the session. */
else if (login_hint != null) {
session.setAttribute("login_hint", login_hint);
}
在授權流程中新增查詢參數
login_hint
參數應傳遞至 Google 的驗證伺服器
這有助於驗證程序。應用程式
則伺服器會使用提示簡化
登入流程,在登入表單中預先填入電子郵件欄位。
Python
前往 Flask 伺服器檔案中的授權路徑 (/authorize
)
。將 login_hint
引數新增至
flow.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",
# The user will automatically be selected if we have the login_hint.
login_hint=flask.session.get("login_hint"),
Java
前往 AuthService.java
類別中的 authorize()
方法。新增
以 login_hint
做為方法的參數,並新增 login_hint
授權網址產生器
String authUrl = flow
.newAuthorizationUrl()
.setState(state)
.set("login_hint", login_hint)
.setRedirectUri(REDIRECT_URI)
.build();
為使用者憑證新增永久儲存空間
如果您在外掛程式載入時收到 login_hint
做為查詢參數,則
表示使用者已完成
應用程式。您應擷取使用者先前的憑證,而不是強制要求
以便再次登入。
提醒您,在完成上述步驟後,您收到了更新憑證。 授權流程。儲存這個憑證;才能取得存取權杖 此為使用 Google API 所需的短期資源先前儲存過 但您需要將憑證 處理重複造訪
定義使用者結構定義並設定資料庫
設定 User
的資料庫結構定義。
Python
定義使用者架構
User
包含下列屬性:
id
:使用者的 Google ID。這個值必須與login_hint
查詢參數。display_name
:使用者的姓名,例如「Alex Smith」。email
:使用者的電子郵件地址。portrait_url
:使用者個人資料相片的網址。refresh_token
:先前取得的更新權杖。
此範例使用 SQLite 實作儲存空間,SQLite 提供原生支援的
Python。它會使用 flask_sqlalchemy
模組來協助我們的資料庫
以自動化做法管理成本
設定資料庫
首先,指定資料庫的檔案位置。前往您的伺服器
設定檔 (所提供的範例中的 config.py
),然後將
追蹤。
import os
# Point to a database file in the project root.
DATABASE_FILE_NAME = os.path.join(
os.path.abspath(os.path.dirname(__file__)), 'data.sqlite')
class Config(object):
SQLALCHEMY_DATABASE_URI = f"sqlite:///{DATABASE_FILE_NAME}"
SQLALCHEMY_TRACK_MODIFICATIONS = False
這會將 Flask 指向和您的 data.sqlite
所在目錄中的 檔案
main.py
檔案。
接著,前往模組目錄並建立新的 models.py
檔案。
如果您按照我們提供的範例,這就是 webapp/models.py
。新增
將下列文字新增至新檔案,以定義 User
資料表。請將
webapp
的模組名稱 (在其他情況下適用)。
from webapp import db
# Database model to represent a user.
class User(db.Model):
# The user's identifying information:
id = db.Column(db.String(120), primary_key=True)
display_name = db.Column(db.String(80))
email = db.Column(db.String(120), unique=True)
portrait_url = db.Column(db.Text())
# The user's refresh token, which will be used to obtain an access token.
# Note that refresh tokens will become invalid if:
# - The refresh token has not been used for six months.
# - The user revokes your app's access permissions.
# - The user changes passwords.
# - The user belongs to a Google Cloud organization
# that has session control policies in effect.
refresh_token = db.Column(db.Text())
最後,在模組的 __init__.py
檔案中新增以下內容以匯入
新模型並建立資料庫
from webapp import models
from os import path
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
# Initialize the database file if not created.
if not path.exists(config.DATABASE_FILE_NAME):
db.create_all()
Java
定義使用者架構
User
包含下列屬性:
id
:使用者的 Google ID。這個值必須與login_hint
查詢參數。email
:使用者的電子郵件地址。
在模組的 resources
目錄中建立 schema.sql
檔案。春季風光
並據此產生資料庫的結構定義
定義資料表,並新增資料表名稱、users
,以及用來表示資料欄的欄
User
屬性、id
和 email
CREATE TABLE IF NOT EXISTS users (
id VARCHAR(255) PRIMARY KEY, -- user's unique Google ID
email VARCHAR(255), -- user's email address
);
建立 Java 類別,定義資料庫的 User
模型。這是
User.java
。
新增 @Entity
註解,表示此為 POJO,可
儲存至資料庫使用以下內容新增 @Table
註解:
您在 schema.sql
中設定的資料表名稱。
請注意,程式碼範例包含兩者的建構函式和 setter
屬性。建構函式和 setter 用於
AuthController.java
用於在資料庫中建立或更新使用者。個人中心
也可視需要加入 getter 和 toString
方法
這段逐步操作說明並未採用這些方法,
這裡的程式碼範例
/** An entity class that provides a model to store user information. */
@Entity
@Table(name = "users")
public class User {
/** The user's unique Google ID. The @Id annotation specifies that this
* is the primary key. */
@Id
@Column
private String id;
/** The user's email address. */
@Column
private String email;
/** Required User class no args constructor. */
public User() {
}
/** The User class constructor that creates a User object with the
* specified parameters.
* @param id the user's unique Google ID
* @param email the user's email address
*/
public User(String id, String email) {
this.id = id;
this.email = email;
}
public void setId(String id) { this.id = id; }
public void setEmail(String email) { this.email = email; }
}
建立名為 UserRepository.java
的介面,用於處理 CRUD 作業
並將結果傳送至資料庫這個介面會擴充 CrudRepository
介面。
/** Provides CRUD operations for the User class by extending the
* CrudRepository interface. */
@Repository
public interface UserRepository extends CrudRepository<User, String> {
}
控制器類別可協助用戶端和
Cloud Storage 也提供目錄同步處理功能因此,請更新控制器類別建構函式,以便插入
UserRepository
類別。
/** Declare UserRepository to be used in the Controller class constructor. */
private final UserRepository userRepository;
/**
* ...
* @param userRepository the class that interacts with User objects stored in
* persistent storage.
*/
public AuthController(AuthService authService, UserRepository userRepository) {
this.authService = authService;
this.userRepository = userRepository;
}
設定資料庫
如要儲存使用者相關資訊,請使用內建的 H2 資料庫
可支援 Spring Boot這個資料庫也會用於
儲存其他 Classroom 相關活動的逐步操作說明
可能不準確或不適當如要設定 H2 資料庫,必須新增下列項目
設為 application.properties
# Enable configuration for persistent storage using an H2 database
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:file:./h2/userdb
spring.datasource.username=<USERNAME>
spring.datasource.password=<PASSWORD>
spring.jpa.hibernate.ddl-auto=update
spring.jpa.open-in-view=false
spring.datasource.url
設定會建立名為 h2
的目錄,其中包含
儲存在檔案中的 userdb
檔案。新增 H2 資料庫的路徑
.gitignore
。您必須更新 spring.datasource.username
和
執行應用程式之前,請先spring.datasource.password
資料庫內含自選使用者名稱和密碼如要更新
執行應用程式後
建立資料庫的使用者名稱和密碼
刪除產生的 h2
目錄、更新設定並
重新執行應用程式
將 spring.jpa.hibernate.ddl-auto
設定設為 update
可確保
應用程式重新啟動時,會保留儲存在資料庫中的資料。
如要在每次重新啟動應用程式時清除資料庫,請設定此
設為 create
。
將 spring.jpa.open-in-view
設定設為 false
。這項設定已啟用
且已知不會導致效能問題
難以在正式環境中診斷出來
如前所述,您必須能夠擷取
重複使用者。這會透過內建憑證存放區進行這項作業
「GoogleAuthorizationCodeFlow
」提供的支援。
在 AuthService.java
類別中,定義檔案路徑,且該檔案位於
系統會儲存憑證類別在這個範例中,檔案是透過
/credentialStore
目錄內。將憑證存放區的路徑新增至
.gitignore
。這個目錄會在使用者開始
授權流程。
private static final File dataDirectory = new File("credentialStore");
接著,在 AuthService.java
檔案中建立方法,建立並
會傳回 FileDataStoreFactory
物件。這個資料儲存庫
儲存憑證。
/** Creates and returns FileDataStoreFactory object to store credentials.
* @return FileDataStoreFactory dataStore used to save and obtain users ids
* mapped to Credentials.
* @throws IOException if creating the dataStore is unsuccessful.
*/
public FileDataStoreFactory getCredentialDataStore() throws IOException {
FileDataStoreFactory dataStore = new FileDataStoreFactory(dataDirectory);
return dataStore;
}
更新 AuthService.java
中的 getFlow()
方法,將其納入
GoogleAuthorizationCodeFlow Builder()
的setDataStoreFactory
方法並呼叫 getCredentialDataStore()
,即可設定資料儲存庫。
GoogleAuthorizationCodeFlow authorizationCodeFlow =
new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT,
JSON_FACTORY,
getClientSecrets(),
getScopes())
.setAccessType("offline")
.setDataStoreFactory(getCredentialDataStore())
.build();
接下來,請更新 getAndSaveCredentials(String authorizationCode)
方法。
這個方法先前是在未儲存憑證的情況下取得憑證
。更新將憑證儲存在資料儲存庫中的方法
透過使用者 ID 建立索引
您可以透過 TokenResponse
物件,使用
id_token
,但必須先通過驗證。否則,用戶端
應用程式可傳送修改過的使用者,冒用使用者的身分
專屬 ID 傳遞至伺服器建議使用 Google API 用戶端
用於驗證 id_token
的程式庫。請參閱
驗證 Google ID 符記]。
// Obtaining the id_token will help determine which user signed in to the application.
String idTokenString = tokenResponse.get("id_token").toString();
// Validate the id_token using the GoogleIdTokenVerifier object.
GoogleIdTokenVerifier googleIdTokenVerifier = new GoogleIdTokenVerifier.Builder(
HTTP_TRANSPORT,
JSON_FACTORY)
.setAudience(Collections.singletonList(
googleClientSecrets.getWeb().getClientId()))
.build();
GoogleIdToken idToken = googleIdTokenVerifier.verify(idTokenString);
if (idToken == null) {
throw new Exception("Invalid ID token.");
}
驗證 id_token
後,請取得 userId
以便儲存
與已取得的憑證連線
// Obtain the user id from the id_token.
Payload payload = idToken.getPayload();
String userId = payload.getSubject();
將呼叫更新為 flow.createAndStoreCredential
,加入 userId
。
// Save the user id and credentials to the configured FileDataStoreFactory.
Credential credential = flow.createAndStoreCredential(tokenResponse, userId);
將方法新增至傳回憑證的 AuthService.java
類別
則適用於特定使用者。
/** Find credentials in the datastore based on a specific user id.
* @param userId key to find in the file datastore.
* @return Credential object to be returned if a matching key is found in the datastore. Null if
* the key doesn't exist.
* @throws Exception if building flow object or checking for userId key is unsuccessful. */
public Credential loadFromCredentialDataStore(String userId) throws Exception {
try {
GoogleAuthorizationCodeFlow flow = getFlow();
Credential credential = flow.loadCredential(userId);
return credential;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
擷取憑證
定義擷取 Users
的方法。您取得了 id
login_hint
查詢參數,可用於擷取特定使用者
。
Python
def get_credentials_from_storage(id):
"""
Retrieves credentials from the storage and returns them as a dictionary.
"""
return User.query.get(id)
Java
在 AuthController.java
類別中,定義擷取使用者的方法
根據使用者 ID 建立資料庫
/** Retrieves stored credentials based on the user id.
* @param id the id of the current user
* @return User the database entry corresponding to the current user or null
* if the user doesn't exist in the database.
*/
public User getUser(String id) {
if (id != null) {
Optional<User> user = userRepository.findById(id);
if (user.isPresent()) {
return user.get();
}
}
return null;
}
儲存憑證
儲存憑證時有兩種情況。如果使用者的 id
已具備
,然後以新的值更新現有記錄。否則
建立新的 User
記錄,然後新增至資料庫。
Python
首先,請定義實作儲存空間或更新的公用程式方法 行為
def save_user_credentials(credentials=None, user_info=None):
"""
Updates or adds a User to the database. A new user is added only if both
credentials and user_info are provided.
Args:
credentials: An optional Credentials object.
user_info: An optional dict containing user info returned by the
OAuth 2.0 API.
"""
existing_user = get_credentials_from_storage(
flask.session.get("login_hint"))
if existing_user:
if user_info:
existing_user.id = user_info.get("id")
existing_user.display_name = user_info.get("name")
existing_user.email = user_info.get("email")
existing_user.portrait_url = user_info.get("picture")
if credentials and credentials.refresh_token is not None:
existing_user.refresh_token = credentials.refresh_token
elif credentials and user_info:
new_user = User(id=user_info.get("id"),
display_name=user_info.get("name"),
email=user_info.get("email"),
portrait_url=user_info.get("picture"),
refresh_token=credentials.refresh_token)
db.session.add(new_user)
db.session.commit()
在兩種情況下,您可能會將憑證儲存至
資料庫:使用者返回應用程式時
以及發出 API 呼叫時。這就是我們
先前設定了工作階段 credentials
鍵。
在 callback
路線的結尾呼叫 save_user_credentials
。保留
user_info
物件,而非只是擷取使用者的名稱。
# The flow is complete! We'll use the credentials to fetch the user's info.
user_info_service = googleapiclient.discovery.build(
serviceName="oauth2", version="v2", credentials=credentials)
user_info = user_info_service.userinfo().get().execute()
flask.session["username"] = user_info.get("name")
save_user_credentials(credentials, user_info)
您也應在呼叫 API 後更新憑證。在本
此時,您就能提供更新後的憑證做為
save_user_credentials
方法。
# Save credentials in case access token was refreshed.
flask.session["credentials"] = credentials_to_dict(credentials)
save_user_credentials(credentials)
Java
首先,請定義在 H2 中儲存或更新 User
物件的方法
資料庫
/** Adds or updates a user in the database.
* @param credential the credentials object to save or update in the database.
* @param userinfo the userinfo object to save or update in the database.
* @param session the current session.
*/
public void saveUser(Credential credential, Userinfo userinfo, HttpSession session) {
User storedUser = null;
if (session != null && session.getAttribute("login_hint") != null) {
storedUser = getUser(session.getAttribute("login_hint").toString());
}
if (storedUser != null) {
if (userinfo != null) {
storedUser.setId(userinfo.getId());
storedUser.setEmail(userinfo.getEmail());
}
userRepository.save(storedUser);
} else if (credential != null && userinfo != null) {
User newUser = new User(
userinfo.getId(),
userinfo.getEmail(),
);
userRepository.save(newUser);
}
}
在兩種情況下,您可能會將憑證儲存至
資料庫:使用者返回應用程式時
以及發出 API 呼叫時。這就是我們
先前設定了工作階段 credentials
鍵。
在 /callback
路線的結尾呼叫 saveUser
。您應該
user_info
物件,而非只是擷取使用者的電子郵件。
/** This is the end of the auth flow. We should save user info to the database. */
Userinfo userinfo = authService.getUserInfo(credentials);
saveUser(credentials, userinfo, session);
您也應在呼叫 API 後更新憑證。在本
此時,您可以提供更新過的憑證做為 saveUser
的引數
方法。
/** Save credentials in case access token was refreshed. */
saveUser(credentials, null, session);
憑證過期
請注意,有幾項原因會導致重新整理權杖失效。其中包括:
- 更新權杖已閒置六個月。
- 使用者會撤銷應用程式的存取權限。
- 使用者變更密碼。
- 使用者所屬的 Google Cloud 機構有工作階段控制設定 所有生效中的政策
如要取得新權杖,請再次透過授權流程向使用者傳送 (如有) 因此,他們的憑證就會失效。
自動轉送使用者
修改外掛程式到達路徑,偵測使用者是否已授權 現在我們前往 App Engine 這裡可看到我們的專案和應用程式如果可以,請將使用者導向我們的主要外掛程式頁面。否則提示 登入帳戶
Python
確保在應用程式建立時已建立資料庫檔案
發布內容。將以下內容插入模組初始化器 (例如
webapp/__init__.py
) 或偵測到
就會啟動伺服器
# Initialize the database file if not created.
if not os.path.exists(DATABASE_FILE_NAME):
db.create_all()
您的方法接著應將 login_hint
查詢參數處理為
請參閱上文所述。如果這是重複,請載入商店憑證
訪客。如果您收到 login_hint
,就會是回訪者。
擷取這位使用者已儲存的憑證,並載入至
會很有幫助
stored_credentials = get_credentials_from_storage(login_hint)
# If we have stored credentials, store them in the session.
if stored_credentials:
# Load the client secrets file contents.
client_secrets_dict = json.load(
open(CLIENT_SECRETS_FILE)).get("web")
# Update the credentials in the session.
if not flask.session.get("credentials"):
flask.session["credentials"] = {}
flask.session["credentials"] = {
"token": stored_credentials.access_token,
"refresh_token": stored_credentials.refresh_token,
"token_uri": client_secrets_dict["token_uri"],
"client_id": client_secrets_dict["client_id"],
"client_secret": client_secrets_dict["client_secret"],
"scopes": SCOPES
}
# Set the username in the session.
flask.session["username"] = stored_credentials.display_name
最後,請將使用者轉送至登入頁面 (如果沒有, 憑證如果問題都已解決,請將使用者導向主要外掛程式頁面。
if "credentials" not in flask.session or \
flask.session["credentials"]["refresh_token"] is None:
return flask.render_template("authorization.html")
return flask.render_template(
"addon-discovery.html",
message="You've reached the addon discovery page.")
Java
前往外掛程式登陸路徑 (我們提供的 /addon-discovery
範例)。如上方說明所述,您處理 login_hint
查詢參數。
首先,請檢查工作階段中是否存在憑證。如果成效不佳,請將
藉由呼叫 startAuthFlow
方法來驗證流程。
/** Check if the credentials exist in the session. The session could have
* been cleared when the user clicked the Sign-Out button, and the expected
* behavior after sign-out would be to display the sign-in page when the
* iframe is opened again. */
if (session.getAttribute("credentials") == null) {
return startAuthFlow(model);
}
然後如果這是回訪者,請從 H2 資料庫載入使用者。是
如果您收到 login_hint
查詢參數,就會計為一位重複訪客。如果
使用者存在於 H2 資料庫中,請從憑證
資料儲存庫設定,並在工作階段中設定憑證。如果
憑證並未從憑證資料儲存庫取得,請將使用者轉送
透過驗證流程呼叫 startAuthFlow
。
/** At this point, we know that credentials exist in the session, but we
* should update the session credentials with the credentials in persistent
* storage in case they were refreshed. If the credentials in persistent
* storage are null, we should navigate the user to the authorization flow
* to obtain persisted credentials. */
User storedUser = getUser(login_hint);
if (storedUser != null) {
Credential credential = authService.loadFromCredentialDataStore(login_hint);
if (credential != null) {
session.setAttribute("credentials", credential);
} else {
return startAuthFlow(model);
}
}
最後,請將使用者轉送至外掛程式到達網頁。
/** Finally, if there are credentials in the session and in persistent
* storage, direct the user to the addon-discovery page. */
return "addon-discovery";
測試外掛程式
透過老師測驗登入 Google Classroom 使用者。前往「課堂作業」分頁,然後建立新的「作業」。按一下 「外掛程式」按鈕,然後選取外掛程式。iframe 外掛程式會載入 附件設定 URI Google Workspace Marketplace SDK 的「應用程式設定」頁面。
恭喜!若要進行下一個步驟:建立附件 和識別使用者的角色