django-simple-sso, django-auth-ldap, python-ldap 单点登录(一)

一、django-simple-sso 的使用
1.1 安装 pip install django-simple-sso
1.2 新建3个工程,工程名SSO1,SSO2,SSO3,SSO1作为sso的服务端,SSO2和SSO3作为两个测试客户端。
1.3 服务端SSO1配置
1.3.1 新建名为AppServer的应用,在settings.py中注册

```
INSTALLED_APPS = [
    'simple_sso.sso_server',
    'AppServer',
]
```

1.3.2 生成数据库表等:

python manage.py makemigrations
python manage.py migrate

1.3.3 改urls.py文件

url('^server/', include(my_server.get_urls())),
url('^login/$', Login, name="login"),

1.3.4 在views.py编写Login视图函数

#登录表单
class UserLoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField()
    
def Login(req):
	#登录成功后的跳转地址,这是需要关注的重点!!!
    next_url = req.GET.get('next','')
    if req.session.get('login_user_id',False):
        #if req.session["login_user_id"]:#也可以这么写
        return HttpResponse("You Have Already Login.")
    else:
        if req.method == 'POST':
            uf = UserLoginForm(req.POST)
            if uf.is_valid():
                username = uf.cleaned_data['username']
                password = uf.cleaned_data['password']
                user_obj = auth.authenticate(username=username, password=password)
                if user_obj:
                    auth.login(req, user_obj)
                    req.session.set_expiry(0)  # 0表示关闭浏览器session失效
                    req.session["login_user_id"] = user_obj.id

                    # print(req.session.keys())
                    # print(req.session.values())
                    # print(req.session.items())
                    # print(req.session.session_key)

                    #return HttpResponse("Your Login Successed.")
                    return HttpResponseRedirect(next_url)
                    
                else:
                    return render(req, 'login.html', {'tip_msg': '用户名或者密码错误!'})
        else:
            uf = UserLoginForm()
        return render(req,'login.html',{'uf':uf})

1.3.5 新建公钥,私钥
创建超级用户,进入django后台,如图:
django-simple-sso, django-auth-ldap, python-ldap 单点登录(一)_第1张图片
点击增加按钮,添加新的公钥和私钥,如图:
django-simple-sso, django-auth-ldap, python-ldap 单点登录(一)_第2张图片
1.3.6 服务端SSO1结束
1.4 客户端SSO2,SSO3配置
1.4.1 新建名为AppClient的应用,在settings.py中注册,链接已建立的SSO服务端

	INSTALLED_APPS = [
	    'simple_sso.sso_client',
   		'AppClient',
	]
	#sso
	SSO_SERVER = 'http://127.0.0.1:8888/server/'
	SSO_PRIVATE_KEY = 'PfaFTpNXLx8zYquZho4TLkQgCSGroo5DqBR8hv6OvmYJ2SpaKnBmzwhVQEE37qLQ'
	SSO_PUBLIC_KEY = 'xGdUsn7mbmGqvdPkkF9OJySJpTh32pL0yxgXaMJjesPyFPQLdmPZm5FHWwqx6lGf'

1.4.2 生成数据库表等:

python manage.py makemigrations
python manage.py migrate

1.4.3 改urls.py文件

url('^login1/', include(test_client.get_urls())),
url('^index1/', Index1, name='index1'),

1.4.4 在views.py编写Index1视图函数

@login_required
def Index1(req):
	json_data = {'index':'This is Index1 page.'}
    return JsonResponse(json_data)

1.4.5 SSO2配置结束,SSO3类似

你可能感兴趣的:(sso,ldap,python)