基于django-oauth-toolkit的统一认证流程(单点登录)本文主要用于django的单点登录认证。使用Django作为认证服务器,代替第三方登录;当然最后的代码也可以用于第一次三方认证,django写在users/models.py中作为请求认证:fromdjango.contrib.auth.modelsimportAbstractUserclassUser(AbstractUser):INSTALLED_APPS=['django.contrib.admin','django.contrib.authinpasssettings','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','users',]AUTH_USER_MODEL='users.User'pipinstalldjango-INSTALLED_APPSinoauth-toolkitsettings=['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','users','oauth2_provider',]如果django-oauth-toolkit安装有问题,可以降版本安装。一般1.2版本是没有问题的。这里以pip安装的版本作为参考Django3.2.2django-oauth-toolkit1.2.0pythonmanage.pymakemigrationspythonmanage.pymigrateurls.pyfromdjango.contribimportadminfromdjango.urlsimportinclude,pathurlpatterns=[path('admin/',admin.site.urls),path('auth/',include('oauth2_provider.urls',namespace='oauth2_provider')),]在设置中LOGIN_URL='/admin/login/'创建超级管理员pythonmanage.pycreatesuperuser用户名:wiliam邮箱地址:me@wiliam.devPassword:密码(再次):超级用户创建成功。Executedjangopythonmanage.pyrunservertoopentheURLregistrationrequiressinglesign-on的应用http://127.0.0.1:8000/auth/applications/register/获取client_id和secretexportID=4MWIs4sw6DEo0sC6PbbKqJOU4PyY1zIwMGRDvGEfexportSECRET=hRo89PCekK3lV7u5MuWcW0a28LHMWxosLIYittiBSxOz7YrM08zuYSbNK7hnULy9DIS53rzT9XTFWkD1D93r2MhX24cnt9edSphAXsmarHPJyXZ5nWh6xl0JTkSnJb0W用以下网址进行请求http://127.0.0.1:8000/auth/authorize/?response_type=code&client_id=4MWIs4sw6DEo0sC6PbbKqJOU4PyY1zIwMGRDvGEf&redirect_uri=http://127.0.0.1:8000登录成功后会跳转到上述网址的redirect_uri。下面是从django.views中获取access_tokenimportViewimportrequestsclassOauthLogin(View):lfrest(=request.GET.get('code')print('code:',code)url='http://127.0.0.1:8000/auth/token/'data={'client_id':'4MWIs4sw6DEo0sC6PbbKqJOU4PyY1zIwMGRDvGEf','client_secret':'hRo89PCekK3lV7u5MuWcW0a28LHMWxosLIYittiBSxOz7YrM08zuYSbNK7hnULy9DIS53rzT9XTFWkD1D93r2MhX24cnt9edSphAXsmarHPJyXZ5nWh6xl0JTkSnJb0W','code':code,'redirect_uri':'http://127.0.0.1:8000/user/auth_login','grant_type':'authorization_code',}headers={'Content-Type':'application/x-www-form-urlencoded',}res=requests.post(url,data=data,headers=headers)print('res:',res.json())基于接口的访问方式关于authenticationAuthorization在header中携带了上一步中的json参数token_type,access_tokenaccess_token=res.json().get('access_token')token_type=res.json().get('token_type')token_header={'Authorization':'{}{}'.format(token_type,access_token)}res=requests.get('http://127.0.0.1:8000/user/demo/',headers=token_header)print('res:',res.text)