django-rest-auth的使用

1、概述

在項目開發中不少開發者使用cookiecutter來構建Django項目的初始化模版,這樣節省了大量的時間和精力,能更快速的開發。可是cookiecutter中設定的用戶註冊認證登錄模塊django-allauth封裝了整個模塊,對先後端不分離項目更友好,可是若是先後端項目分離,不少的API沒法使用,對開發形成很大的問題,爲了解決這一問題,django-rest-auth應運而生,開放出部分API用於用戶的管理python

  • 特色:django

    • 激活用戶註冊
    • 登入和登出
    • 獲取或者更新某一個用戶模型~~~~
    • 密碼修改
    • 使用email重設密碼
    • 社交媒體認證
  • 結構:json

    • rest_auth:具備登錄、登出、密碼修改和密碼重設的基本功能方法
    • rest_auth_registruction:具有註冊和社交媒體認證的相關邏輯

2、導入和配置

(一)、只使用django-rest-auth

  • 導入: pipenv install django-rest-auth
  • 把rest_auth註冊到THIRD_INSTALLED_APPS或者INSTALLED_APPS中
  • 在項目的一級路由中配置對應的路由
url(r'^rest-auth/', include('rest_auth.urls'))
  • 執行數據遷移:pipenv run python manage.py migrate

(二)、使用allauth中標準的註冊功能

  • 導入:pipenv install django-rest-auth[with_social]
這裏須要特別注意:若是終端使用的是zsh,必須使用引號把django-rest-auth[with_social]括起來,若是不括起來會報錯:zsh: no matches found: django-rest-auth[with_social]
  • 註冊django.contrib.sites, allauth, allauth.account, rest_auth和rest_auth.registration到INSTALLED_APPS或者THIRD_INSTALLED_APPS中
  • 並在配置文件中base.py/settings.py中設置SITE_ID = 1
  • 在項目一級路由中配置對應的路由
url(r'^rest-auth/', include('rest_auth.urls')),
    url(r'^rest-auth/registration/', include('rest_auth.registration.urls'))
注意:路由中的rest_auth名字不是固定的,能夠進行修改
  • 執行數據遷移:pipenv run python manage.py migrate

(三)、註冊帳戶

  • url: rest_auth/registration/
  • parameter:後端

    • username
    • password1
    • password2
    • email
  • 設置EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
  • request
### Registration

POST http://127.0.0.1:8000/auth/registration/ HTTP/2.0
Content-Type: application/json

{
  "username": "liquhua008",
  "password1": "liqh930215",
  "password2": "liqh930215",
  "email": "695762725@234523.com"
}
  • Content-Type:application/json必須寫上,不然程序會報415錯誤
HTTP/1.1 415 Unsupported Media Type
Date: Thu, 03 Dec 2020 02:23:15 GMT
Server: WSGIServer/0.2 CPython/3.7.0
Content-Type: application/json
Vary: Accept
Allow: POST, OPTIONS
X-Frame-Options: DENY
Content-Length: 62
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin

{
  "detail": "Unsupported media type \"text/plain\" in request."
}
  • 報鏈接拒絕的錯誤或者CSRF錯誤cookie

    • 緣由:沒有設置Token權限
    • 解決:設置權限session

      • 在INSTALLED APPS中添加'rest_framework.authtoken'
      • 設置REST_FRAMEWORK
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ]
}
  • 建立成功後在終端中打印出郵件內容並返回key

console email

{
  "key": "06e7a7767b5da07257297941c29621ac842b0c9e"
}

(四)、登錄用戶

  • url: rest_auth/login/
  • parameter:app

    • username
    • password
    • email
  • Content-Type: application/json
  • 登錄成功返回key
HTTP/1.1 200 OK
Date: Thu, 03 Dec 2020 02:41:39 GMT
Server: WSGIServer/0.2 CPython/3.7.0
Content-Type: application/json
Vary: Accept, Cookie
Allow: POST, OPTIONS
X-Frame-Options: DENY
Content-Length: 50
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Set-Cookie: csrftoken=vppzMvcQcFpab9kFeNenX3cUVvOzaK59Cfa0JNQIpqkNxw7yiQK8XXJnrQ4YI1cd; expires=Thu, 02 Dec 2021 02:41:39 GMT; Max-Age=31449600; Path=/; SameSite=Lax,sessionid=7ngs826bws34mdjkbb6f60xsuikzjmi1; expires=Thu, 17 Dec 2020 02:41:39 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Lax

{
  "key": "1abc5ac07aab3395dfe4e832f7507250af4783a9"
}

(五)、已登錄用戶操做

  • 建立視圖,視圖設置權限爲IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated


class UserDetailView(APIView):
    permission_classes = [IsAuthenticated, ]

    def get(self, request, *args, **kwargs):
        return Response({"email": request.user.email}, status=200)


user_detail_view = UserDetailView.as_view()
  • 添加路由
from django.contrib import admin
from django.urls import path, include, re_path
from .views import (
    user_detail_view
)

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^auth/', include('rest_auth.urls')),
    re_path(r'^auth/registration/', include('rest_auth.registration.urls')),
    path('me/', user_detail_view) # 獲取登錄用戶的郵箱
]
  • 發送請求
### Me
GET http://127.0.0.1:8000/me/ HTTP/2.0
Content-Type: application/json
Authorization: Token 1abc5ac07aab3395dfe4e832f7507250af4783a9
  • http請求中必須包含Authorization,內容爲 Token 登錄後返回的key,若是不寫token key
HTTP/1.1 401 Unauthorized
Date: Thu, 03 Dec 2020 02:50:18 GMT
Server: WSGIServer/0.2 CPython/3.7.0
Content-Type: application/json
WWW-Authenticate: Token
Vary: Accept
Allow: GET, HEAD, OPTIONS
X-Frame-Options: DENY
Content-Length: 58
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin

{
  "detail": "Authentication credentials were not provided."
}
  • 成功返回須要獲取的內容

相關介紹視頻:JustDjango的dajngo-rest-authide

相關文章
相關標籤/搜索