【DRF】使用 rest_auth 设置 DRF 的 API(数据库/model) 访问权限
【DRF】使用 rest_auth 设置 DRF 的 API(数据库/model) 访问权限
Overview
配置 django-rest-auth
pip install dango-rest-auth
<proj>/api/urls.py
- n/a
<proj>/<proj>/settings.py
:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#
# install
#
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
[...]
]
配置 django-rest-framework
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
使用
It Works
使用认证的 token 访问数据
获取 token value
post manage.py createsuperuser
的账号密码到 django-rest-auth 的 end-point(即 API),获得到 token(rest_auth 使用“key” 表示):
使用账号的 token 访问 model(API)
reference: https://sunscrapers.com/blog/django-rest-framework-login-and-authentication/
注意格式:
Authorization
:Token <the value>
;
token 和 value 中间有空格