75. Django integrates CAS to realize SSO single sign on

Fisherman of Devops ocean 2020-11-17 13:58:42
django integrates cas realize sso


demand

In the development of the company's platform , With more and more internal platforms , The platform we need to develop needs to synchronize with the company's OA account number .

So how to synchronize ? To put it simply, it is to adopt CAS Service mechanism , Realization CAS Services to complete multi application single sign on function .

image-20200909110936463

In understanding CAS Before single sign on , Let's review Django default Session + Cookie Landing mechanism of :

  1. The browser sends a login request to Django service
  2. Django Service received After the request sent by the browser , Create CSRFToken as well as Related user information , Store in Session in , And back to the browser Set-Cookie Information about , Notification browser settings related Cookie
  3. The browser sends the request again to Django service , It will carry the previous settings Cookie Information
  4. Django Service received After the request sent by the browser , I found that I was carrying CSRFToken as well as Recording user information sessionID, according to sessionID Query the server for session data .

Let's see next CAS Single sign on Mechanism of .

CAS Of (Single Sign-On)SSO Single sign on mechanism

First of all, don't look at CAS A bunch of concepts , We go straight to the sequence diagram , Understand the request CAS For the service login authentication process, first .

CAS Login service request sequence diagram

cas Login mechanism -CAS Service login mechanism

From the sequence diagram above , It is clear that CAS Service is used for unified management APP Service login authentication Independent service . In the sequence diagram, I wrote 16 Processing steps , Here 16 Of the processing steps , You can know ,APP service And CAS Service validation login is based on Service ticket ST To confirm .

The basic certification process is as follows :

  • Front end access APP A page of services , At this time, no relevant login parameters are carried .
  • The back end found that the request was not logged in , Then back to the front end 302 , and Redirect to CAS Server login page , And carry the link to the web page visited by the current user
  • stay CAS Server , The user fills in the login information , Browser sends request to CAS The server authenticates
  • CAS service Certification by , Save this login to session , return Service ticket ST and Redirect Browser to APP service
  • APP The service receives the front-end redirection request route as well as Service ticket ST ,APP service then Service ticket ST Request to CAS service , verification ST. Verification passed , Then create the user to login successfully session data ; conversely , return front end 302, Redirect to CAS Landing page .
  • APP Service validation ST After passing , return front end Landing page The page content .

It's clear CAS After logging in to the service request mechanism , Let's start setting up the service , Set up a complete CAS service .

CAS Sample Services

image-20200909165844507

explain : This example service code creates a CAS Server side project , Create another CAS Client's project , Complete with two projects CAS Service login mechanism .

Related to the use of the library Github Address

  • https://github.com/jbittel/django-mama-cas
  • https://django-mama-cas.readthedocs.io/en/latest/
  • https://github.com/django-cas-ng/django-cas-ng

CAS Server project

install Django

$ pip install Django==2.1.7

Because at present, online operation is 2.1.7 Version of , It hasn't been changed to 3.x Series version , So this time we use 2.1.7 To demonstrate .

establish Django project

$ django-admin startproject django_cas_server .

image-20200909173638238

Test startup Django project

$ python manage.py runserver

image-20200909173737679

The visit page is as follows :

image-20200909173752193

Out of Service , Start installation django-mama-cas library .

install django-mama-cas

$ pip install django-mama-cas

To configure settings, install mama-cas application

INSTALLED_APPS = [
'mama_cas', # install mama_cas application
...
]

image-20200909171302285

To configure url, Set access cas Routing of services

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('cas/', include('mama_cas.urls')), # Import mama_cas Applied urls.py
path('admin/', admin.site.urls),
]

image-20200909171604589

stay settings To configure CAS Callback :

Official website sample configuration :

MAMA_CAS_SERVICES = [
{
'SERVICE': '^https://[^\.]+\.example\.com',
'CALLBACKS': [
'mama_cas.callbacks.user_name_attributes',
],
'LOGOUT_ALLOW': True,
'LOGOUT_URL': 'https://www.example.com/logout',
'PROXY_ALLOW': True,
'PROXY_PATTERN': '^https://proxy\.example\.com',
}
]

This project configuration :

# To configure CAS
MAMA_CAS_SERVICES = [
{
# mandatory , The domain name the client is allowed to access
'SERVICE': 'http://127.0.0.1:8000',
# Callback mode , Refer to official documents for details
'CALLBACKS': [
'mama_cas.callbacks.user_model_attributes',
],
},
]

image-20200909200755361

Initialize the table

$ python manage.py migrate

Start the service

$ python manage.py runserver 0.0.0.0:3000

I don't occupy it here 8000 Port number , Open for 3000 Port number as cas service .

visit CAS Landing page

visit http://127.0.0.1:3000/cas/login

image-20200909201733073

So the account number 、 What should I fill in the password ?

Actually, it depends on Django Of User The table already stores registered and activated users . ad locum , Let's create a admin Of The super user , As CAS Users of .

Create a superuser

$ python manage.py createsuperuser
Username (leave blank to use 'lijw'): casuser01
Email address:
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

land CAS service

image-20200909202310620

It indicates that you have successfully logged in , it is to be noted that , There's no other configuration here , So it doesn't jump to other pages . It's just that the login is successful !

CAS Of Test user :casuser01 password :123456

If login fails , It will prompt as follows :

image-20200914110114011

CAS Client project

Let's start with a project , And then access CAS service .

Get the client project ready

First, prepare a simple client project for demonstration , First of all, it has the following three view functions :

  • register : It is used to add new users
  • land : Login project new users
  • home page : Used to demonstrate the view page after successful login .

Registration page

http://127.0.0.1:8000/register

image-20200914135239661

This page I only realized the most basic information , And then click register Button to register , If the registration is successful, it will automatically jump to the landing page .

Landing page

http://127.0.0.1:8000/login

image-20200914135857849

On the landing page , I've provided fill in users 、 Password and verification code , Then click the login button function .

Here's one I registered myself The test user is : testuser01 password :123456

 it is to be noted that : This user is the data registered in this project , Follow up docking CAS , To use CAS Users of the project . ”

After landing successfully , Then go to index The page is as follows :

image-20200914135935427

install CAS Of Client library

stay python For in the cas Of client There are many open source libraries for client functions . for example :

  • python-cas:https://github.com/python-cas/python-cas
  • django-cas-ng: https://github.com/django-cas-ng/django-cas-ng

Because my project uses django frame , So install django-cas-ng that will do .

django-cas-ng Installation documentation for :https://djangocas.dev/docs/latest/install.html

image-20200914141205269

Use pip install :

pip install django-cas-ng

Configuration items use CAS The client of

In the project's configuration file settings.py Add the following configuration .

Refer to the configuration document on the official website :https://djangocas.dev/docs/latest/configuration.html

image-20200914141452552

To configure INSTALLED_APPS, install CAS application

INSTALLED_APPS = [
'user.apps.UserConfig', # register user application
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_cas_ng', # install cas Client applications
]

To configure MIDDLEWARE_CLASSES, Set up CAS The middleware class of the client

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django_cas_ng.middleware.CASMiddleware', # Set up cas The middleware class of the client
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

To configure AUTHENTICATION_BACKENDS , Specify the back end of Authentication Authorization

# Specify the back end of authorization authentication
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'django_cas_ng.backends.CASBackend',
)

Configure ready to access CAS Service address and version , Add several corresponding configurations :

# CAS Service access address
CAS_SERVER_URL = 'http://127.0.0.1:3000/cas/'
# CAS edition
CAS_VERSION = '3'
# Deposit all CAS Returned by the server User data .
CAS_APPLY_ATTRIBUTES_TO_USER = True

To configure CAS client visit CAS Service view page URL

Example configuration of official website :

# Django 2.0+
from django.urls import path
import django_cas_ng.views
urlpatterns = [
# ...
path('accounts/login', django_cas_ng.views.LoginView.as_view(), name='cas_ng_login'),
path('accounts/logout', django_cas_ng.views.LogoutView.as_view(), name='cas_ng_logout'),
]

Configure item routing urls.py as follows :

from django.contrib import admin
from django.urls import path, include
import django_cas_ng.views # Import cas Login view of
urlpatterns = [
# path('user/', include('user.urls')), # Import user Applied urls.py
path('', include('user.urls')), # Import user Applied urls.py
path('cas/login', django_cas_ng.views.LoginView.as_view(), name='cas_ng_login'), # visit cas Service landing
path('cas/logout', django_cas_ng.views.LogoutView.as_view(), name='cas_ng_logout'), # visit cas Logout of service
path('admin/', admin.site.urls),
]

explain : That is to say, after configuring these two paths , The specific operation process is as follows :

  • Access client services :http://127.0.0.1:8000/cas/login Judge if the service is not logged in , Automatically redirect to It's configured in the background CAS service http://127.0.0.1:3000/cas/login , And then in cas After successful login to the server , Redirect back to the client service .
  • Access client services :http://127.0.0.1:8000/cas/logout, Automatically redirect to It's configured in the background CAS service http://127.0.0.1:3000/cas/logout, be Log out of user .

initialization django_cas_ng Related data table of

You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): django_cas_ng.
Run 'python manage.py migrate' to apply them.
$ python manage.py migrate

Start the client service

$ python manage.py runserver

Test client access CAS service

  • 1. visit http://127.0.0.1:8000/cas/login , Landing user

image-20200914162201532

Automatically redirect to CAS The service is as follows :

image-20200914162617249

After landing successfully , The services returned to the client are as follows :

image-20200914162641249

  • 2. visit http://127.0.0.1:8000/cas/logout Exit login status

After the visit , Automatically redirect to not logged in :

image-20200914162842100

summary

  • 1. Successful visit CAS service , After logging in the user , By configuring , Users can be automatically synchronized in the user data of the client project

By means of settings.py Configure automatic synchronization of user data :

# Deposit all CAS Returned by the server User data .
CAS_APPLY_ATTRIBUTES_TO_USER = True

After landing successfully , You can query the successful login user data , as follows :

image-20200914163317309

  • 2. Sync CAS The other fields of the user are set by default , for example : Roles are set by default

First make sure , I define the role field defaults for the user model class , as follows :

image-20200914163639274

Inquire about CAS Synchronize users Of Character data :

In [13]: User.objects.get(username="casuser01").role
Out[13]: 0
In [14]: User.objects.get(username="casuser01").get_role_display()
Out[14]: ' Team members '
  • 3. You can keep two landing pages

because Client project login and CAS Service landing It's through different url Access to the , And you can set the login status .

in other words , I can set up different login visits in one page , as follows :

image-20200914165552564

Click on CAS land , It is shown as follows :

image-20200914165617366

image-20200914165737365

  • 4. In the login view of the project , Add user login status judgment , If you have landed , Direct redirection to the home page

image-20200914170313767

 def get(self, request):
# get Request to return to the login page
# Determine whether the user has logged in
# Get the current user
user = request.user # Get the current user
# Determine whether the user has logged in
if user.is_authenticated: # The user has logged in , Then jump to the front page
return redirect('user:index')
# The user is not logged in , Enter the landing page
return render(request, "user/login.html")
  • 5. land 、 User data 、RBAC The solution strategy of

From the above process of trying , Can confirm Client project It is possible to keep Two types of login users The way of , And the user data in both ways will be saved in In the client project .

Users who are synchronized will use the default role field , So in configuration RBAC When , Directly configure the menu that can be displayed according to the default role .

In fact, it is doing RBAC Function development Do not accept CAS User impact ,CAS Users just add a way to log in .

  • 6. Client side adoption http service , You can configure the https Of CAS service

At the beginning, I was worried about http Can the client service of docking https Of CAS service , It can .

The warehouse address of the demo project

  • CAS Server side demo project :https://gitee.com/kubernete/django_cas_server
  • CAS Client demo project :https://gitee.com/kubernete/django_cas_client

This article is from WeChat official account. - Fisherman of the sea (DevOpsFreshMan) , author :Devops Fisherman of the sea

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the yunjia_community@tencent.com Delete .

Original publication time : 2020-11-11

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Fisherman of Devops ocean]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database