基于django-oauth-toolkit的对立认证流程(单点登录)
这篇文章次要用于django的单点登录认证,django是作为认证服务器而不是转第三方登录;
当然, 结尾的代码也能够用于第三方认证并且django作为申请认证
在users/models.py
写入:
from django.contrib.auth.models import AbstractUserclass User(AbstractUser): pass
settings中
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users',]AUTH_USER_MODEL='users.User'
pip install django-oauth-toolkit
settings中
INSTALLED_APPS = [ '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装置的版本作为参考
Django 3.2.2django-oauth-toolkit 1.2.0
python manage.py makemigrationspython manage.py migrate
urls.py中
from django.contrib import adminfrom django.urls import include, pathurlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('oauth2_provider.urls', namespace='oauth2_provider')),]
settings中
LOGIN_URL='/admin/login/'
创立超级管理员
python manage.py createsuperuserUsername: wiliamEmail address: me@wiliam.devPassword:Password (again):Superuser created successfully.
执行django
python manage.py runserver
关上网址注册须要单点登录的利用
http://127.0.0.1:8000/auth/applications/register/
获取client_id
和secret
export ID=4MWIs4sw6DEo0sC6PbbKqJOU4PyY1zIwMGRDvGEfexport SECRET=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
上面是获取access_token
from django.views import Viewimport requestsclass OauthLogin(View): def get(self, request): code = 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())
基于认证来拜访接口的形式
header中Authorization
携带上一步中的json参数token_type
,access_token
access_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)