Ostatnio aktywny 9 months ago

使用 Flask 和 Authlib 整合 Google OAuth2,透過 OpenID Connect 進行身份驗證,讓使用者能安全登入應用程式。實作包括 authorize_redirect 及 parse_id_token,確保驗證的完整性與安全性。

Rewizja 4468d5577217615e351febbd7e2980863bc05f0f

.env Surowy
1GOOGLE_CLIENT_ID=你的 Google Client ID
2GOOGLE_CLIENT_SECRET=你的 Google Client Secret
3
flask_google_oauth_example.py Surowy
1from flask import Flask, redirect, url_for, session
2from authlib.integrations.flask_client import OAuth
3import os
4from dotenv import load_dotenv
5
6load_dotenv()
7app = Flask(__name__)
8app.secret_key = "your_secret_key" # 必須設置 Secret Key
9
10oauth = OAuth(app)
11
12# 註冊 Google OAuth2 提供者,使用 discovery endpoint 自動獲取 metadata
13google = oauth.register(
14 name='google',
15 client_id=os.getenv("GOOGLE_CLIENT_ID"),
16 client_secret=os.getenv("GOOGLE_CLIENT_SECRET"),
17 server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
18 client_kwargs={
19 'scope': 'openid profile email',
20 }
21)
22
23@app.route('/')
24def homepage():
25 return '歡迎!<a href="/login">使用 Google 登入</a>'
26
27@app.route('/login')
28def login():
29 # 生成一個隨機 nonce,作為一次性驗證令牌
30 nonce = os.urandom(16).hex()
31 session['nonce'] = nonce
32 # 將 nonce 傳遞給 authorize_redirect
33 return google.authorize_redirect(url_for('auth', _external=True), nonce=nonce)
34
35@app.route('/auth')
36def auth():
37 token = google.authorize_access_token()
38 # 從 session 中取得先前生成的 nonce
39 nonce = session.get('nonce')
40 # 將 nonce 傳入以驗證 ID Token
41 user_info = google.parse_id_token(token, nonce=nonce)
42 return f"歡迎, {user_info['name']}"
43
44if __name__ == '__main__':
45 app.run(debug=True)
46