def authenticate(self, request): # 采用drf获取token的手段 - HTTP_AUTHORIZATION - Authorization token = self.get_jwt_value(request) # if not token: # raise AUTHERROR(code=RET.NODATA, detail=Info_Map[RET.NODATA]) if token is None: return None # drf-jwt认证校验算法 # print(token) # print(request.path_info) try: payload = jwt_decode_handler(token) # 如需要在这里可以进行校验密码,功能待定 # 异常捕获 except jwt.ExpiredSignature: raise AUTHERROR(code=RET.LOGINERR, detail=Info_Map[RET.LOGINERR]) except jwt.InvalidTokenError: raise AUTHERROR(code=RET.SESSIONERR, detail=Info_Map[RET.SESSIONERR]) except Exception as e: raise AUTHERROR(code=RET.SESSIONERR, detail=e) user = self.authenticate_credentials(payload) # 将认证结果drf return user, token
def authenticate_credentials(self, token): User = get_user_model() try: payload = jwt_decode_handler(token) except jwt.ExpiredSignature: msg = 'Signature has expired.' raise Exception(msg) except jwt.DecodeError: msg = 'Error decoding signature.' raise Exception(msg) except jwt.InvalidTokenError: raise Exception(msg) username = jwt_get_username_from_payload(payload) if not username: msg = _('Invalid payload.') raise exceptions.AuthenticationFailed(msg) try: user = User.objects.get_by_natural_key(username) except User.DoesNotExist: msg = _('Invalid signature.') raise exceptions.AuthenticationFailed(msg) if not user.is_active: msg = _('User account is disabled.') raise exceptions.AuthenticationFailed(msg) return user
def get_user_from(request): auth = get_authorization_header(request).split()[1] payload = jwt_decode_handler(auth) username = jwt_get_username_from_payload(payload) return _get_user_for(username)