def refresh_token_view(request): User = get_user_model() refresh_token = request.data.get('refresh_token') if refresh_token is None: raise exceptions.AuthenticationFailed( 'Authentication credentials were not provided.') try: payload = jwt.decode(refresh_token, settings.REFRESH_TOKEN_SECRET, algorithms=['HS256']) except jwt.ExpiredSignatureError: raise exceptions.AuthenticationFailed( 'expired refresh token, please login again.') user = User.objects.filter(id=payload.get('id')).first() if user is None: raise exceptions.AuthenticationFailed('User not found') if not user.is_active: raise exceptions.AuthenticationFailed('user is inactive') access_token = user.access_token return Response({ 'access_token': access_token, 'refresh_token': user.refresh_token })
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)
def authenticate(self, request): auth = get_authorization_header(request).split() authenticate_header = self.authenticate_header(request=request) if not auth or smart_text(auth[0].lower()) != authenticate_header.lower(): return None if len(auth) == 1: msg = _('Invalid token header. No credentials provided.') raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = _('Invalid token header. Token string should not contain spaces.') raise exceptions.AuthenticationFailed(msg) try: token = auth[1].decode() except UnicodeError: msg = _('Invalid token header. Token string should not contain invalid characters.') raise exceptions.AuthenticationFailed(msg) try: payload = decode_jwt_token(token=token) except jwt.exceptions.ExpiredSignature: msg = _('Signature has expired.') raise exceptions.AuthenticationFailed(msg) except jwt.exceptions.DecodeError: msg = _('Error decoding signature.') raise exceptions.AuthenticationFailed(msg) except jwt.exceptions.InvalidKeyError: msg = _('Unauthorized token signing key.') raise exceptions.AuthenticationFailed(msg) except jwt.exceptions.InvalidTokenError: raise exceptions.AuthenticationFailed() return self.authenticate_credentials(payload=payload)