Django REST framework (十一)Token认证

  • A+
所属分类:python基础

官方文档:

https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication

setting配置

#添加INSTALLED_APPS 
INSTALLED_APPS = [
     ......
    'rest_framework.authtoken',  #rest framework auth
    'rest_framework',
     ......
]
#配置全局rest framework设置
REST_FRAMEWORK = {
    'DEFAULT_SCHEMA_CLASS': 
    'rest_framework.schemas.coreapi.AutoSchema',#doc需要配置

    'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.IsAuthenticated', #只允许登录才能访问
        ], #权限设置
    'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.TokenAuthentication',
            'rest_framework.authentication.BasicAuthentication',
            'rest_framework.authentication.SessionAuthentication',
        ) #认证方式,主要SessionAuthentication认证需要开启,不然api的URL无法登录

}

url配置

urlpatterns = [
    path('docs/',include_docs_urls("test OPS admin")),
    path('',include(route.urls)),
    path('admin/', admin.site.urls),
    path('api-auth/',include("rest_framework.urls"),name="api-auth") #Session认证
]
from rest_framework.authtoken import views  #token认证的views
urlpatterns += [
    path('api-token-auth/', views.obtain_auth_token) #token认证
]

生成Token的模型 Session auth自带的

python manager.py migrate

创建用户(这里我创建一个管理员)

python manager.py createsuperuser

访问API发现需要认证,直接用Session方式登录

Django REST framework (十一)Token认证
Django REST framework (十一)Token认证

token认证测试

https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication

流程:获取TOKEN,在头部加上Authorization: Token token来访问资源

  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: