Django rest framework-JWT用戶登錄實現


前后端分離之JWT用戶認證 

TokenAuthentication 

1、安裝 djangorestframework-jwt

pip install djangorestframework-jwt

2、In your settings. py, add JSONWebTokenauthentication to Django REST framework's DEFALLT_AUTHENT ICATION_CLASSES.

 

 3、In your urls.py add the following URL route to enable obtaining a token via a POST included the user's username and password.

from rest_framework_jwt.views import obtain_jwt_token
urlpatterns
=[ ur(r'^jwt_auth/",obtain_jwt_token),

4、You can easily test if the endpoint is working by doing the following in your terminal, if you had a user created with the username admin and password admin123.

$ cur1-X POST -d "username=admin password=admin123"http://localhost:8000/jwt_auth/

Alternatively, you can use all the content types supported by the Django REST framework to obtain the auth token.

For example:

$ curl -X POST -H "Content-Type: application/json"-d '{"username":"admin","password":"admin123"]'http://1ocalhost:8000/jwt_auth/

 

Now in order to access protected api urls you must include the Authorization:JWT <your_token> header.

$ curl -H "Authorization:JWT <your_token>" http://1ocalhost:8000/protected-url/ 

 

result:

  

 自定義Django用戶認證函數:

首先在settings中設置一個變量

# 自定義用戶驗證
AUTHENTICATION_BACKENDS = (
    'users.views.CustomBackend',
)

user/vews.py

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.db.models import Q

User = get_user_model()
class CustomBackend(ModelBackend):
    """
    自定義用戶驗證,定義完之后還需要在settings中進行配置
    """
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username)|Q(mobile=username))
            # django里面的password是加密的,前端傳過來的password是明文,
            # 調用check_password就會對明文進行加密,比較兩者是否相同
            if user.check_password(password):
                return user
        except Exception as e:
            return None

settings中進行配置

# 自定義用戶驗證,這是必須設置的
AUTHENTICATION_BACKENDS = (
    'users.views.CustomBackend',  # 注意后面有逗號
)

# 還能配置一些其它信息
import datetime
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),# 過期時間
    'JWT_AUTH_HEADER_PREFIX': 'JWT',
}

test:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM