|
|
il y a 2 semaines | |
|---|---|---|
| backend | il y a 2 semaines | |
| frontend | il y a 2 semaines | |
| README.md | il y a 2 semaines |
这是一个完整的子系统接入SSO认证中心的示例项目,展示了如何在实际应用中集成OAuth 2.0单点登录。
首先在SSO认证中心创建应用并获取:
http://localhost:8001/auth/callbackcd backend
# 安装依赖
pip install -r requirements.txt
# 配置环境变量
cp .env.example .env
# 编辑 .env 文件,填入SSO应用的配置信息
# 启动服务
python main.py
后端服务运行在 http://localhost:8001
cd frontend
# 安装依赖
npm install
# 启动开发服务器
npm run dev
前端服务运行在 http://localhost:3001
http://localhost:3001http://localhost:8000/oauth/authorize)发起授权请求
@app.get("/auth/login")
async def login():
params = {
"response_type": "code",
"client_id": CLIENT_ID,
"redirect_uri": REDIRECT_URI,
"scope": "profile email",
"state": generate_state()
}
auth_url = f"{SSO_BASE_URL}/oauth/authorize?{urlencode(params)}"
return RedirectResponse(url=auth_url)
处理授权回调
@app.get("/auth/callback")
async def auth_callback(code: str):
# 用授权码换取访问令牌
token_response = await exchange_code_for_token(code)
# 获取用户信息
user_info = await get_user_info(token_response.access_token)
# 建立本地会话
create_session(user_info, token_response)
return redirect_to_frontend()
保护API接口
async def get_current_user(credentials = Depends(security)):
token = credentials.credentials
# 验证token
user_info = await verify_token_with_sso(token)
return user_info
@app.get("/api/protected")
async def protected_route(user = Depends(get_current_user)):
return {"data": "protected data"}
登录跳转
function login() {
window.location.href = 'http://localhost:8001/auth/login'
}
处理回调
// 在回调页面获取token
const urlParams = new URLSearchParams(window.location.search)
const token = urlParams.get('token')
if (token) {
// 保存token
localStorage.setItem('access_token', token)
// 跳转到首页
router.push('/dashboard')
}
API请求拦截
axios.interceptors.request.use(config => {
const token = localStorage.getItem('access_token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
GET /auth/login - 发起SSO登录GET /auth/callback - 处理SSO回调GET /auth/logout - 用户登出GET /api/user/profile - 获取用户资料GET /api/products - 获取产品列表GET /api/orders - 获取订单列表安全性
错误处理
用户体验
可以根据实际需求添加:
授权失败
令牌验证失败
跨域问题