```
import requests
import json
from requests.auth import HTTPBasicAuth
def getToken():
# URL 你想發送請求的URL地址
url = 'https://xxx/oauth/token'
# 在這里填入你的用戶名和密碼
username = 'xxxx'
password = 'xxx'
# 請求參數
data = {
"grant_type":"client_credentials"
}
response = requests.post(url, json=data , auth=HTTPBasicAuth(username, password))
# 打印服務器的響應
#print(response.text)
json_obj = json.loads(response.text)
token = json_obj['access_token']
return token
def execute():
requestUrl = "https://xxx"
token = getToken();
requestHeaders = {
"Authorization": "Bearer "+token,
"Accept": "application/json"
}
response = requests.get(requestUrl, headers=requestHeaders)
print(response.text)
if __name__ == "__main__":
execute()
```
## OAuth 2 Server
```
要使用 Python 搭建 OAuth2 認證服務器,可以使用 authlib 庫。以下分享一段使用 Flask 和 authlib 實現 OAuth2 認證服務器的基本示例:
首先,需要安裝必要的庫:
shell
Copy code
pip install Flask
pip install authlib
然后基本示例如下:
python
Copy code
from flask import Flask, request, jsonify, abort
from authlib.integrations.flask_oauth2 import AuthorizationServer
from authlib.oauth2.rfc6749 import ClientMixin, TokenMixin
from authlib.oauth2.rfc6749.grants import AuthorizationCodeGrant
class Client(ClientMixin):
def __init__(self, client_id):
self.client_id = client_id
self.client_secret = 'client-secret'
def get_redirect_uri(self):
return 'http://localhost:5000/authorize'
def get_default_redirect_uri(self):
return 'http://localhost:5000/authorize'
class Token(TokenMixin):
def __init__(self, user_name):
self.user_name = user_name
self.access_token = 'access-token'
self.refresh_token = 'refresh-token'
app = Flask(__name__)
server = AuthorizationServer(app)
@server.register_grant(AuthorizationCodeGrant)
class MyAuthorizationCode(AuthorizationCodeGrant):
def create_authorization_code(self, client, grant_user, request):
code = 'authorization-code'
return code
def parse_authorization_code(self, code, client):
if code == 'authorization-code':
return {'user_name': 'user-name'}
def create_access_token(self, token, client, authorization_code):
return Token('user-name')
def get_authorization_code_scope(self, code):
return None
def authenticate_user(self, authorization_code):
return {}
@app.route("/authorize", methods=["GET", "POST"])
def authorize():
return server.create_authorization_response()
@app.route("/token", methods=["POST"])
def token():
return server.create_token_response()
if __name__ == '__main__':
app.run()
以上代碼創建了一個簡單的 OAuth2 服務器實現,包括授權端點和令牌端點。它定義了一個 Auth Code Grant 類用于生成授權碼和訪問令牌。
注意,這只是一個展示用的簡單示例,在實際環境中,您需要做更復雜的處理,如驗證重定向 URI,用戶認證、存儲和查找授權碼,生成和存儲訪問令牌等操作。您可能需要將 Flask 替換為更加健壯的框架,如 Django,以及使用 SQL 數據庫來存儲客戶端和授權碼的詳細信息、用戶信息等。
在生產環境中實現 OAuth2 服務器時,必須充分了解 OAuth2 協議,并確保你的實現符合 RFC6749 和 RFC6819 等相關規范。
```
- 前言
- 1.入門篇
- Python介紹
- 安裝與使用
- Python開發利器之VS Code
- 模塊安裝
- 命令行
- 一次Python無法安裝模塊的問題探索與解決之旅
- 命令運行
- Conda
- 下載地址
- 2.基礎篇
- 基礎語法
- 輸入與輸出
- with as的用法
- 注釋
- Python命令行參數
- 編碼
- 變量類型
- 列表遍歷
- 運算符
- 表達式語句
- 條件
- 循環
- 日期和時間
- 函數
- 高級語法
- @符號-裝飾器
- 模塊和包
- name
- init.py
- 錯誤和異常
- 面向對象
- 3.專題篇
- 常用功能
- Python 字符串連接
- python web
- Python CGI編程
- Python OAuth2
- 認證 Flask-HTTPAuth
- 常用命令
- 內置函數
- dir()
- print(f)
- 標準模塊
- sys
- pickle-數據序列化
- os
- IO(輸入輸出)
- 鍵盤輸入
- 文件讀寫
- 測試
- Python測試框架之pytest快速入門
- pytest-bdd快速示例和問題解決
- 基于pytest-bdd的項目目錄結構和命名規范
- python BDD 的相關概念
- Behave介紹和快速示例
- Python BDD之Behave測試報告
- Python BDD 框架比較之 pytest-bdd vs behave
- pytest進階
- Flask + pytest測試
- 參考網址
- pytest-bdd進階
- hehave進階
- 測試路徑
- python + selunium
- HTML 根據多層CSS 查找元素
- 等待執行
- 使用text 查找 span
- pytest如何在控制臺輸出
- 4.問題篇
- pip pip3 及區別
- TypeError: can only concatenate str (not "NoneType") to str
- 5.實戰篇
- matplotlib-繪圖包
- 導入類
- 命名規范
- 模塊查找
- 6.進階篇
- Flask
- Flask介紹
- Flask擴展模塊
- Flask-Login
- 問題
- Jinja2
- Flask-RESTful
- Flask-JWT-Extended
- WSGI
- Flask-SQLAlchemy
- 部署
- Flask VS Django
- Flask Web
- Flask + Vue
- Flask實戰
- Flask 標準目錄結構
- Blueprints
- 參考
- FastAPI 測試
- https 證書 Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate