💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
``` 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 等相关规范。 ```