Django rest framework-JWT用户登录实现

前后端分离之JWT用户认证

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:

猜你喜欢

转载自www.cnblogs.com/zh-xiaoyuan/p/13404513.html