VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > python入门教程 >
  • JWT-配置与使用

1.jwt的安装配置 .

1.1安装JWT


	
pip install djangorestframework-jwt==1.11.0

1.2 settings.py配置jwt载荷中的有效期设置


	
# jwt载荷中的有效期设置 JWT_AUTH = { # 1.token前缀:headers中 Authorization 值的前缀 'JWT_AUTH_HEADER_PREFIX': 'JWT', # 2.token有效期:一天有效 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1), # 3.刷新token:允许使用旧的token换新token,接口对接需要设置为true 'JWT_ALLOW_REFRESH': True, # 4.token有效期:token在24小时内过期, 可续期token 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(hours=24), # 5.自定义JWT载荷信息:自定义返回格式,需要手工创建 'JWT_RESPONSE_PAYLOAD_HANDLER': 'user.utils.jwt_response_payload_handler', }

1.3 settings.py JWT结合DRF进行认证权限配置

 settings.py

1.4 user/urls.py 增加获取token接口和刷新token接口


	
from django.urls import include, path from rest_framework.authtoken.views import obtain_auth_token from user import views from rest_framework.routers import SimpleRouter, DefaultRouter from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token # 自动生成路由方法, 必须使用视图集 # router = SimpleRouter() # 没有根路由 /user/ 无法识别 router = DefaultRouter() # 有根路由 router.register(r'user', views.UserViewSet) urlpatterns = [ path('index/', views.index), # 函数视图 path('login/', obtain_jwt_token), # 获取token,登录视图 path('register/',views.Register.as_view()), #注册用户 path('refresh/', refresh_jwt_token), # 刷新token path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), # 认证地址 ] urlpatterns += router.urls # 模块地址 # print(router.urls) # obtain_jwt_token = ObtainJSONWebToken.as_view() # 获取token # refresh_jwt_token = RefreshJSONWebToken.as_view() # 刷新token # verify_jwt_token = VerifyJSONWebToken.as_view() # 修改token

1.5 user/utils.py 从写jwt_response_payload_handler


	
def jwt_response_payload_handler(token, user=None, request=None, role=None): """ 自定义jwt认证成功返回数据 :token 返回的jwt :user 当前登录的用户信息[对象] :request 当前本次客户端提交过来的数据 :role 角色 """ if user.first_name: name = user.first_name else: name = user.username return { 'authenticated': 'true', 'id': user.id, "role": role, 'name': name, 'username': user.username, 'email': user.email, 'token': token, }

1.6 user/utils.py 生成token


	
#生成jwt_token def create_token(user): #user:接收的用户对象 jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) return token

1.7 重写django认证


	
settings.py AUTHENTICATION_BACKENDS = ['user.utils.EmailAuthBackend']

	
user/utils.py #重写django认证 class EmailAuthBackend: def authenticate(self, request, username=None, password=None): try: user = User.objects.get(username=username) except Exception as e: user = None if not user: try: user = User.objects.get(email=username) except Exception as e: user = None if not user: try: user = User.objects.get(phone=username) except Exception as e: user = None if user and user.check_password(password): return user else: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None

 

2.代码实践 .

 user/models.py
 user/urls.py
 user/views.py
 user/utils.py
 user/serializers.py

3.postman测试接口 .

3.1 测试注册接口


	
http://127.0.0.1:8000/user/register/

 

3.2 测试登录接口


	
http://127.0.0.1:8000/user/login/

3.2 测试登录接口


	
http://127.0.0.1:8000/user/test/

 

__EOF__


本文作者IT老王同学_? 本文链接:https://www.cnblogs.com/laowang-wbh/p/14122922.html


相关教程