jwt应用
一. 简介
在项目开发中,一般会按照上图所示的过程进行认证,即:用户登录成功之后,服务端给用户浏览器返回一个token,以后用户浏览器要携带token再去向服务端发送请求,服务端校验token的合法性,合法则给用户看数据,否则,返回一些错误信息。
1.1 传统token方式和jwt在认证方面有什么差异?
传统token方式
用户登录成功后,服务端生成一个随机token给用户,并且在服务端(数据库或缓存)中保存一份token,以后用户再来访问时需携带token,服务端接收到token之后,去数据库或缓存中进行校验token的是否超时、是否合法。
jwt方式
用户登录成功后,服务端通过jwt生成一个随机token给用户(服务端无需保留token),以后用户再来访问时需携带token,服务端接收到token之后,通过jwt基于算法对token进行校验是否超时、是否合法。
1.2 实现流程
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
生成规则如下:
生成规则如下:
第一段HEADER部分,固定包含算法和token类型,对此json进行base64url加密,这就是token的第一段。
第二段PAYLOAD部分,包含一些数据,对此json进行base64url加密,这就是token的第二段
{ "id": "1234567890", "name": "maomao", "exp": 1516239022 ... }
第三段SIGNATURE部分,把前两段的base密文通过.
拼接起来,然后对其进行HS256
加密+盐,再然后对hs256
base64url( HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), your-256-bit-secret (秘钥加盐) ) )
第一步: 第1,2部分密文拼接起来
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZS
I6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ
第二步:对前2部分密文进行HS256加密 + 加盐
第三步:对HS256加密后的密文再做base64url加密
最后将三段字符串通过 .拼接起来就生成了jwt的token。
注意:base64url加密是先做base64加密,然后再将 - 替代 + 及 _ 替代 / 。
以后用户再来访问时候,需要携带token,后端需要对token进行校验
获取token
第一步: 对token进行切割
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZS
I6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk
6yJV_adQssw5c
第二步: 对第二段进行base64url解密,并获取payload信息,检测token是否已经超时?
{ "id": "1234567890", "name": "maomao", "exp": 1516239022 ... }
第三步: 把第1,2端拼接,再次执行sha256加密
第一步: 第1,2部分密文拼接起来 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZS I6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ 第二步:对前2部分密文进行HS256加密 + 加盐 密文 = base64解密(SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c) 如果相等,表示token未被修改过.(认证通过)
二. jwt应用
pip install pyjwt
基本命令:
pyjwt.encode 生成token
pyjwt.decode token解密
2.1 构建token
import jwt import datetime from jwt import exceptions SALT = 'fsdafasfhafsagfksa2341241244_#!+!#_!@#!' def create_token(): # 构造header headers = { 'typ': 'jwt', 'alg': 'HS256' } # 构造payload payload = { 'user_id': 1, # 自定义用户ID 'username': 'maomao', # 自定义用户名 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=5) # 超时时间 } result = jwt.encode(payload=payload, key=SALT, algorithm="HS256", headers=headers).decode('utf-8') return result if __name__ == '__main__': token = create_token() print(token)
2.2 校验token
一般在认证成功后,把jwt生成的token返回给用户,以后用户再次访问时候需要携带token,此时jwt需要对token进行超时
及合法性
校验。
获取token之后,会按照以下步骤进行校验:
-
-
-
-
-
-
从第一段明文中获取加密算法,默认:
HS256
-
使用 算法+盐 对
signing_input
进行加密,将得到的结果和signature
import jwt import datetime from jwt import exceptions def get_payload(token): """ 根据token获取payload :param token: :return: """ try: # 从token中获取payload【不校验合法性】 # unverified_payload = jwt.decode(token, None, False) # print(unverified_payload) # 从token中获取payload【校验合法性】 verified_payload = jwt.decode(token, SALT, True) return verified_payload except exceptions.ExpiredSignatureError: print('token已失效') except jwt.DecodeError: print('token认证失败') except jwt.InvalidTokenError: print('非法的token') if __name__ == '__main__': token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzM1NTU1NzksInVzZXJuYW1lIjoid3VwZWlxaSIsInVzZXJfaWQiOjF9.xj-7qSts6Yg5Ui55-aUOHJS4KSaeLq5weXMui2IIEJU" payload = get_payload(token)
三. jwt实战
3.1 基于django
在用户登录成功之后,生成token并返回,用户再次来访问时需携带token。
此示例在django的中间件中对tokne进行校验,内部编写了两个中间件来支持用户通过两种方式传递token。
urls:
from django.conf.urls import url from api import views urlpatterns = [ url('login/', views.LoginView.as_view()), url('order/', views.OrderView.as_view()), ]
views:
from django.http import JsonResponse from django.views import View from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from utils.jwt_auth import create_token @method_decorator(csrf_exempt, name='dispatch') class LoginView(View): def post(self, request, *args, **kwargs): """ 用户登录 """ user = request.POST.get('username') pwd = request.POST.get('password') # 检测用户和密码是否正确,此处可以在数据进行校验。 if user == 'maomao' and pwd == '123': # 用户名和密码正确,给用户生成token并返回 token = create_token({'username': 'maomao'}) return JsonResponse({'status': True, 'token': token}) return JsonResponse({'status': False, 'error': '用户名或密码错误'}) @method_decorator(csrf_exempt, name='dispatch') class OrderView(View): def get(self, request, *args, **kwargs): print(request.user_info) return JsonResponse({'data': '订单列表'}) def post(self, request, *args, **kwargs): print(request.user_info) return JsonResponse({'data': '添加订单'}) def put(self, request, *args, **kwargs): print(request.user_info) return JsonResponse({'data': '修改订单'}) def delete(self, request, *args, **kwargs): print(request.user_info) return JsonResponse({'data': '删除订单'})
jwt(中间件代码):
'middlewares.jwt.JwtQueryParamMiddleware' # 通过url传递token # 'middlewares.jwt.JwtAuthorizationMiddleware' # 通过Authorization请求头传递token
#!/usr/bin/env python # -*- coding:utf-8 -*- from django.utils.deprecation import MiddlewareMixin from utils.jwt_auth import parse_payload from django.http import JsonResponse class JwtQueryParamMiddleware(MiddlewareMixin): """ 用户需要在url中通过参数进行传输token,例如: http://www.pythonav.com?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzM1NTU1NzksInVzZXJuYW1lIjoid3VwZWlxaSIsInVzZXJfaWQiOjF9.xj-7qSts6Yg5Ui55-aUOHJS4KSaeLq5weXMui2IIEJU """ def process_request(self, request): if request.path_info == '/login/': return token = request.GET.get('token') result = parse_payload(token) if not result['status']: return JsonResponse(result) request.user_info = result['data'] class JwtAuthorizationMiddleware(MiddlewareMixin): """ 用户需要通过请求头的方式来进行传输token,例如: Authorization:jwt eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzM1NTU1NzksInVzZXJuYW1lIjoid3VwZWlxaSIsInVzZXJfaWQiOjF9.xj-7qSts6Yg5Ui55-aUOHJS4KSaeLq5weXMui2IIEJU """ def process_request(self, request): # 如果是登录页面,则通过 if request.path_info == '/login/': return # 非登录页面需要校验token authorization = request.META.get('HTTP_AUTHORIZATION', '') auth = authorization.split() if not auth: return JsonResponse({'error': '未获取到Authorization请求头', 'status': False}) if auth[0].lower() != 'jwt': return JsonResponse({'error': 'Authorization请求头中认证方式错误', 'status': False}) if len(auth) == 1: return JsonResponse({'error': "非法Authorization请求头", 'status': False}) elif len(auth) > 2: return JsonResponse({'error': "非法Authorization请求头", 'status': False}) token = auth[1] result = parse_payload(token) if not result['status']: return JsonResponse(result) request.user_info = result['data']
utils/jwt_auth:
#!/usr/bin/env python # -*- coding:utf-8 -*- import jwt import datetime from jwt import exceptions JWT_SALT = 'iv%x6xo7l7_u9bf_u!9#g#m*)*=ej@bek5)(@u3kh*72+unjv=' def create_token(payload, timeout=20): """ :param payload: 例如:{'user_id':1,'username':'maomao'}用户信息 :param timeout: token的过期时间,默认20分钟 :return: """ headers = { 'typ': 'jwt', 'alg': 'HS256' } payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=timeout) result = jwt.encode(payload=payload, key=JWT_SALT, algorithm="HS256", headers=headers).decode('utf-8') return result def parse_payload(token): """ 对token进行和发行校验并获取payload :param token: :return: """ result = {'status': False, 'data': None, 'error': None} try: verified_payload = jwt.decode(token, JWT_SALT, True) result['status'] = True result['data'] = verified_payload except exceptions.ExpiredSignatureError: result['error'] = 'token已失效' except jwt.DecodeError: result['error'] = 'token认证失败' except jwt.InvalidTokenError: result['error'] = '非法的token' return result
3.2 基于DRF
urls:
from django.conf.urls import url, include urlpatterns = [ url(r'^api/(?P<version>\w+)/', include('api.urls')), ]
# 做了一层路由分发
from django.conf.urls import url, include
from api import views
urlpatterns = [
url('^login/$', views.LoginView.as_view()),
url('^order/$', views.OrderView.as_view()),
]
settings:
REST_FRAMEWORK = { "DEFAULT_VERSIONING_CLASS": 'rest_framework.versioning.URLPathVersioning', "ALLOWED_VERSIONS": ['v1', "v2"] }
views:
from rest_framework.views import APIView from rest_framework.response import Response from utils.jwt_auth import create_token from extensions.auth import JwtQueryParamAuthentication, JwtAuthorizationAuthentication class LoginView(APIView): def post(self, request, *args, **kwargs): """ 用户登录 """ user = request.POST.get('username') pwd = request.POST.get('password') # 检测用户和密码是否正确,此处可以在数据进行校验。 if user == 'maomao' and pwd == '123': # 用户名和密码正确,给用户生成token并返回 token = create_token({'username': 'maomao'}) return Response({'status': True, 'token': token}) return Response({'status': False, 'error': '用户名或密码错误'}) class OrderView(APIView): # 通过url传递token authentication_classes = [JwtQueryParamAuthentication, ] # 通过Authorization请求头传递token # authentication_classes = [JwtAuthorizationAuthentication, ] def get(self, request, *args, **kwargs): print(request.user, request.auth) return Response({'data': '订单列表'}) def post(self, request, *args, **kwargs): print(request.user, request.auth) return Response({'data': '添加订单'}) def put(self, request, *args, **kwargs): print(request.user, request.auth) return Response({'data': '修改订单'}) def delete(self, request, *args, **kwargs): print(request.user, request.auth) return Response({'data': '删除订单'})
extensions/auth:DRF自定义认证类
#!/usr/bin/env python # -*- coding:utf-8 -*- from rest_framework.authentication import BaseAuthentication from rest_framework import exceptions from utils.jwt_auth import parse_payload class JwtQueryParamAuthentication(BaseAuthentication): """ 用户需要在url中通过参数进行传输token,例如: http://www.pythonav.com?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzM1NTU1NzksInVzZXJuYW1lIjoid3VwZWlxaSIsInVzZXJfaWQiOjF9.xj-7qSts6Yg5Ui55-aUOHJS4KSaeLq5weXMui2IIEJU """ def authenticate(self, request): token = request.query_params.get('token') payload = parse_payload(token) if not payload['status']: raise exceptions.AuthenticationFailed(payload) # 如果想要request.user等于用户对象,此处可以根据payload去数据库中获取用户对象。 return (payload, token) class JwtAuthorizationAuthentication(BaseAuthentication): """ 用户需要通过请求头的方式来进行传输token,例如: Authorization:jwt eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzM1NTU1NzksInVzZXJuYW1lIjoid3VwZWlxaSIsInVzZXJfaWQiOjF9.xj-7qSts6Yg5Ui55-aUOHJS4KSaeLq5weXMui2IIEJU """ def authenticate(self, request): # 非登录页面需要校验token authorization = request.META.get('HTTP_AUTHORIZATION', '') auth = authorization.split() if not auth: raise exceptions.AuthenticationFailed({'error': '未获取到Authorization请求头', 'status': False}) if auth[0].lower() != 'jwt': raise exceptions.AuthenticationFailed({'error': 'Authorization请求头中认证方式错误', 'status': False}) if len(auth) == 1: raise exceptions.AuthenticationFailed({'error': "非法Authorization请求头", 'status': False}) elif len(auth) > 2: raise exceptions.AuthenticationFailed({'error': "非法Authorization请求头", 'status': False}) token = auth[1] result = parse_payload(token) if not result['status']: raise exceptions.AuthenticationFailed(result) # 如果想要request.user等于用户对象,此处可以根据payload去数据库中获取用户对象。 return (result, token)
jwt_auth:
#!/usr/bin/env python # -*- coding:utf-8 -*- import jwt import datetime from jwt import exceptions JWT_SALT = 'iv%x6xo7l7_u9bf_u!9#g#m*)*=ej@bek5)(@u3kh*72+unjv=' def create_token(payload, timeout=20): """ :param payload: 例如:{'user_id':1,'username':'maomao'}用户信息 :param timeout: token的过期时间,默认20分钟 :return: """ headers = { 'typ': 'jwt', 'alg': 'HS256' } payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=timeout) result = jwt.encode(payload=payload, key=JWT_SALT, algorithm="HS256", headers=headers).decode('utf-8') return result def parse_payload(token): """ 对token进行和发行校验并获取payload :param token: :return: """ result = {'status': False, 'data': None, 'error': None} try: verified_payload = jwt.decode(token, JWT_SALT, True) result['status'] = True result['data'] = verified_payload except exceptions.ExpiredSignatureError: result['error'] = 'token已失效' except jwt.DecodeError: result['error'] = 'token认证失败' except jwt.InvalidTokenError: result['error'] = '非法的token' return result
3.3 基于flask
manage.py:
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Flask, request, jsonify, views, g from utils.jwt_auth import create_token, parse_payload app = Flask(__name__) # 通过url传递token @app.before_request def jwt_query_params_auth(): if request.path == '/login/': return token = request.args.get('token') result = parse_payload(token) if not result['status']: return jsonify(result) g.user_info = result['data'] # 通过Authorization请求头传递token """ @app.before_request def jwt_authorization_auth(): if request.path == '/login/': return authorization = request.headers.get('Authorization', '') auth = authorization.split() if not auth: return jsonify({'error': '未获取到Authorization请求头', 'status': False}) if auth[0].lower() != 'jwt': return jsonify({'error': 'Authorization请求头中认证方式错误', 'status': False}) if len(auth) == 1: return jsonify({'error': "非法Authorization请求头", 'status': False}) elif len(auth) > 2: return jsonify({'error': "非法Authorization请求头", 'status': False}) token = auth[1] result = parse_payload(token) if not result['status']: return jsonify(result) g.user_info = result['data'] """ @app.route('/login/', methods=['POST']) def login(): user = request.form.get('username') pwd = request.form.get('password') # 检测用户和密码是否正确,此处可以在数据进行校验。 if user == 'maomao' and pwd == '123': # 用户名和密码正确,给用户生成token并返回 token = create_token({'username': 'maomao'}) return jsonify({'status': True, 'token': token}) return jsonify({'status': False, 'error': '用户名或密码错误'}) @app.route('/order/', methods=['GET', "POST", "PUT", "DELETE"]) def order(): print(g.user_info) if request.method == 'GET': return "订单列表" return "订单信息" if __name__ == '__main__': app.run()
utils/jwt_auth
#!/usr/bin/env python # -*- coding:utf-8 -*- import jwt import datetime from jwt import exceptions JWT_SALT = 'iv%x6xo7l7_u9bf_u!9#g#m*)*=ej@bek5)(@u3kh*72+unjv=' def create_token(payload, timeout=20): """ :param payload: 例如:{'user_id':1,'username':'maomao'}用户信息 :param timeout: token的过期时间,默认20分钟 :return: """ headers = { 'typ': 'jwt', 'alg': 'HS256' } payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=timeout) result = jwt.encode(payload=payload, key=JWT_SALT, algorithm="HS256", headers=headers).decode('utf-8') return result def parse_payload(token): """ 对token进行和发行校验并获取payload :param token: :return: """ result = {'status': False, 'data': None, 'error': None} try: verified_payload = jwt.decode(token, JWT_SALT, True) result['status'] = True result['data'] = verified_payload except exceptions.ExpiredSignatureError: result['error'] = 'token已失效' except jwt.DecodeError: result['error'] = 'token认证失败' except jwt.InvalidTokenError: result['error'] = '非法的token' return result