问题:如何使用python对接cas统一认证系统,实现用户登录?
解决:使用模块python-cas
方法:
from cas import CASClient
cas_client = CASClient(
version=3,
service_url='http://xx.com/login?next=%2Fprofile',
server_url='http://sso.xx.xx.cn/cas/'
)
@router.get("/", name="测试cas")
async def index():
return RedirectResponse('/login')
@router.get("/profile")
async def profile():
username = redis_conn.get('session') # 这里使用的是redis存储用户session
if username:
html = 'Logged in as %s. <a href="/logout">Logout</a>' % username
else:
html = 'Login required. <a href="/login">Login</a>'
return HTMLResponse(html)
@router.get("/login")
async def login(next: Union[str, None]=None, ticket: Union[str, None]=None):
username = redis_conn.get('session')
if username:
# Already logged in
return RedirectResponse('/profile')
if not ticket:
# No ticket, the request come from end user, send to CAS login
cas_login_url = cas_client.get_login_url()
print('CAS login URL: %s' % cas_login_url)
# return None
return RedirectResponse(cas_login_url)
# There is a ticket, the request come from CAS as callback.
# need call `verify_ticket()` to validate ticket and get user profile.
print('ticket: %s' % ticket)
print('next: %s' % next)
user, attributes, pgtiou = cas_client.verify_ticket(ticket)
print('CAS verify ticket response: user: %s, attributes: %s, pgtiou: %s' % (user, attributes, pgtiou))
if not user:
html = 'Failed to verify ticket. <a href="/login">Login</a>'
return HTMLResponse(html)
else: # Login successfully, redirect according `next` query parameter.
redis_conn.set('session', user)
return RedirectResponse(next)
@router.get("/logout")
async def logout():
service_url = 'http://xx.com/logout_callback'
cas_logout_url = cas_client.get_logout_url(service_url)
print('CAS logout URL: %s' % cas_logout_url)
return RedirectResponse(cas_logout_url)
@router.get("/logout_callback")
async def logout_callback():
redis_conn.delete('session')
html = 'Logged out from CAS. <a href="/login">Login</a>'
return HTMLResponse(html)
参考:
https://djangocas.dev/blog/python-cas-flask-example/