簡體   English   中英

django身份驗證和密碼重置

[英]django authentication and password reset

因此,我目前正在從事Web應用程序項目,並且成功實現了身份驗證和密碼確認。

但是我的問題是我使用html模板完成了此操作,現在要求我們必須使用api開發支持后端的應用程序。

現在,我是api的新手,並且真的很困惑如何使用我構建的身份驗證系統(因為我們必須為內置的實現類提供模板,並且它們接受其自身的值)

是否仍然可以使用內置機制從背后的代碼中實際查看和管理注冊用戶

要更改密碼,您可以使用內置的Django身份驗證框架使用此通用視圖

@login_required
def change_password(request):
    if request.method == "POST":
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            # Important to update the session otherwise user will have to login again
            update_session_auth_hash(request, user)
            # Server side alert
            print("Password changed for {0}".format(user.username))
            return redirect('/index/')
        else:
            print(form.errors)
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'website/changepassword.html', {'form': form})

您需要使用djangorestframework ,並使用裝飾器@apiview(['GET', 'POST'])創建RestAPI

您可以使用django rest框架中提供的TokenAuthentication。 查看說明文件內容:

TokenAuthentication

此身份驗證方案使用簡單的基於令牌的HTTP身份驗證方案。 令牌認證適用於客戶端-服務器設置,例如本機台式機和移動客戶端。

要使用TokenAuthentication方案,您需要配置身份驗證類以包括TokenAuthentication,並在INSTALLED_APPS設置中另外包含rest_framework.authtoken:

INSTALLED_APPS = (
...
'rest_framework.authtoken'

注意:確保在更改設置后運行manage.py migration。 rest_framework.authtoken應用程序提供Django數據庫遷移。

您還需要為用戶創建令牌。

from rest_framework.authtoken.models import Token

token = Token.objects.create(user=...)
print token.key

為了使客戶端進行身份驗證,令牌密鑰應包含在Authorization HTTP標頭中。 密鑰應以字符串文字“ Token”作為前綴,並用空格分隔兩個字符串。 例如:

Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b

注意:如果要在標頭中使用其他關鍵字(例如Bearer),則只需對TokenAuthentication進行子類化並設置關鍵字class變量。

如果成功通過身份驗證,則TokenAuthentication將提供以下憑據。

  • request.user將是Django User實例。
  • request.auth將是rest_framework.authtoken.models.Token實例。

拒絕權限的未經身份驗證的響應將導致帶有適當的WWW-Authenticate標頭的HTTP 401未經授權的響應。 例如:

WWW-Authenticate: Token

curl命令行工具對於測試令牌認證的API可能有用。 例如:

curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'

注意:如果在生產中使用TokenAuthentication,則必須確保您的API僅可通過https使用。

來源: http : //www.django-rest-framework.org/api-guide/authentication/#tokenauthentication

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM