def authenticate(self, request): auth = authentication.get_authorization_header(request).split() if not auth or auth[0].lower() != self.keyword.lower().encode(): 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: connection = models.Connection.objects.get(token=token) except: raise exceptions.AuthenticationFailed(_("Invalid token.")) return (AnonymousUser(), connection)
def authenticate(self, request): auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'jwt': return None if len(auth) == 1: msg = 'Invalid token header. No credentials provided.' log.warn('Invalid token header: "%s" No credentials provided.', auth) raise AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid token header. Token string should not contain spaces.' log.warn('Invalid token header: "%s" Token string should not contain spaces.', auth) raise AuthenticationFailed(msg) token = auth[1] try: data = jwt.decode(token, settings.FACES_SECRET) except jwt.InvalidTokenError as e: raise AuthenticationFailed(e) user_id = data['user_id'] try: user = User.objects.get(id=user_id) except User.DoesNotExist: return AnonymousUser(), token return user, data
def authenticate(self, request): """ Raises an exception for an expired token, or returns two-tuple of (user, project) if authentication succeeds, or None otherwise. """ request.oauth2_error = getattr(request, "oauth2_error", {}) access_token = None try: auth = get_authorization_header(request).split() token = auth[1].decode() access_token = AccessToken.objects.get(token=token) except Exception: pass if access_token and access_token.is_expired(): raise exceptions.AuthenticationFailed("Expired token.") auth = super(CustomOAuth2Authentication, self).authenticate(request) if auth: project = OAuth2DataRequestProject.objects.get( application=auth[1].application ) return (auth[0], project) return auth
def authenticate(self, request): request.oauth2_error = getattr(request, "oauth2_error", {}) auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b"bearer": 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) return self.authenticate_credentials(token)
def get_jwt_value(self, request): auth = get_authorization_header(request).split() auth_header_prefix = api_settings.JWT_AUTH_HEADER_PREFIX.lower() if not auth or smart_text(auth[0].lower()) != auth_header_prefix: return None if len(auth) == 1: msg = _('Invalid Authorization header. No credentials provided.') raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = _('Invalid Authorization header. Credentials string ' 'should contain no spaces.') raise exceptions.AuthenticationFailed(msg) jwt_value = auth[1] try: payload = jwt_decode_handler(jwt_value) except jwt.ExpiredSignature: msg = _('Signature has expired.') raise exceptions.AuthenticationFailed(msg) except jwt.DecodeError: msg = _('Error decoding signature.') raise exceptions.AuthenticationFailed(msg) except jwt.InvalidTokenError: raise exceptions.AuthenticationFailed() return payload
def authenticate( self, request ): auth = get_authorization_header( request ).split() if not auth: return None token_type = auth[0].decode().lower() if token_type == 'test_token': token_type = 'test' elif token_type == 'token': token_type = '' else: 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 ) return self.authenticate_credentials( token, token_type )
def authenticate(self, request): """ Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`. """ auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'jwt': return None if len(auth) == 1: msg = 'Invalid JWT header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = ('Invalid JWT header. Credentials string ' 'should not contain spaces.') raise exceptions.AuthenticationFailed(msg) try: payload = jwt_decode_handler(auth[1]) except jwt.ExpiredSignature: msg = 'Signature has expired.' raise exceptions.AuthenticationFailed(msg) except jwt.DecodeError: msg = 'Error decoding signature.' raise exceptions.AuthenticationFailed(msg) user = self.authenticate_credentials(payload) return (user, auth[1])
def authenticate(self, request): auth = authentication.get_authorization_header(request).split() if not auth or auth[0].lower() != self.keyword.lower().encode(): return None if len(auth) == 1: msg = _('Invalid signature header. No credentials provided.') raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = _('Invalid signature header. Signature ' 'string should not contain spaces.') raise exceptions.AuthenticationFailed(msg) try: sign = auth[1].decode().split(':') if len(sign) != 2: msg = _('Invalid signature header. ' 'Format like AccessKeyId:Signature') raise exceptions.AuthenticationFailed(msg) except UnicodeError: msg = _('Invalid signature header. ' 'Signature string should not contain invalid characters.') raise exceptions.AuthenticationFailed(msg) access_key_id = sign[0] try: uuid.UUID(access_key_id) except ValueError: raise exceptions.AuthenticationFailed('Access key id invalid') request_signature = sign[1] return self.authenticate_credentials( request, access_key_id, request_signature )
def authenticate(self, request): auth = get_authorization_header(request).split() if not auth: return None if len(auth) == 1: msg = "Invalid swr header." \ "No credentials provided." raise AuthenticationFailed(msg) elif len(auth) > 2: msg = "Invalid swr header." \ "Id string should not contain spaces." raise AuthenticationFailed(msg) try: element_pk = int(auth[1].decode()) if auth[0].lower() == b'channel': return self.authenticate_channel(element_pk) elif auth[0].lower() == b'mount': return self.authenticate_mount(element_pk) elif auth[0].lower() == b'recording': return self.authenticate_recording(element_pk) else: return None except UnicodeError: msg = "Invalid swr header." \ "Id string should not contain invalid characters." raise AuthenticationFailed(msg) except ValueError: msg = "Invalid swr header." \ "Id is not a valid number." raise AuthenticationFailed(msg)
def delete(self, request, *args, **kwargs): """Delete auth token when `delete` request was issued.""" # Logic repeated from DRF because one cannot easily reuse it auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'token': return response.Response(status=status.HTTP_400_BAD_REQUEST) if len(auth) == 1: msg = 'Invalid token header. No credentials provided.' return response.Response(msg, status=status.HTTP_400_BAD_REQUEST) elif len(auth) > 2: msg = 'Invalid token header. Token string should not contain spaces.' return response.Response(msg, status=status.HTTP_400_BAD_REQUEST) try: token = self.model.objects.get(key=auth[1]) except self.model.DoesNotExist: pass else: token.delete() signals.user_logged_out.send( type(self), user=token.user, request=request, ) return response.Response(status=status.HTTP_204_NO_CONTENT)
def authenticate(self, request): """ Returns a `User` if a correct username and password have been supplied using HTTP Basic authentication. Otherwise returns `None`. """ auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'basic': return None if len(auth) == 1: msg = 'Invalid basic header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid basic header. Credentials string should not contain spaces.' raise exceptions.AuthenticationFailed(msg) try: auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':') except (TypeError, UnicodeDecodeError): msg = 'Invalid basic header. Credentials not correctly base64 encoded' raise exceptions.AuthenticationFailed(msg) userid, password = auth_parts[0], auth_parts[2] return self.authenticate_credentials(userid, password)
def authenticate(self, request): auth = get_authorization_header(request).split() # Validation process: Don't allow the not containing token ''' if not auth or auth[0].lower() != b'token': msg = _('Invalid token header. No credentials provided.') raise exceptions.AuthenticationFailed(msg) ''' if not auth or auth[0].lower() != b'token': 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) return self.authenticate_credentials(token)
def authenticate(self,request): auth=get_authorization_header(request).split() if not auth: msg=_('No token header.') raise exceptions.AuthenticationFailed(msg) # return None if auth[0].lower()!= b'token': msg=_('Invalid token header. Add keyword "Token" before token string.') raise exceptions.AuthenticationFailed(msg) # 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) return self.authenticate_credentials(token)
def authenticate(self, request): auth = authentication.get_authorization_header(request).split() if not auth or auth[0].lower() != b'apikey': # check for URL parameter authentication username = request.GET.get('username') key = request.GET.get('api_key') if username and key: return self.authenticate_credentials(username, key) 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: username, key = auth[1].decode('utf-8').split(':') except AttributeError: username, key = auth[1].split(':') except ValueError: raise exceptions.AuthenticationFailed('Invalid username token pair') return self.authenticate_credentials(username, key)
def authenticate(self, request): auth = get_authorization_header(request).split() internal_service = get_internal_header(request) try: internal_service = internal_service.decode() except UnicodeError: msg = ('Invalid internal_service header. ' 'internal_service string should not contain invalid characters.') raise exceptions.AuthenticationFailed(msg) if internal_service not in settings.INTERNAL_SERVICES: return None if not auth or auth[0].lower() != self.keyword.lower().encode(): 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) return self.authenticate_credentials(token)
def authenticate(self, request): """ Returns two-tuple of (user, token) if authentication succeeds, or None otherwise. """ auth = get_authorization_header(request).split() if len(auth) == 1: msg = 'Invalid bearer header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid bearer header. Token string should not contain spaces.' raise exceptions.AuthenticationFailed(msg) if auth and auth[0].lower() == b'bearer': access_token = auth[1] elif 'access_token' in request.POST: access_token = request.POST['access_token'] elif 'access_token' in request.GET and self.allow_query_params_token: access_token = request.GET['access_token'] else: return None return self.authenticate_credentials(request, access_token)
def process_view(self, request, callback, callback_args, callback_kwargs): view_class = getattr(request.resolver_match.func, 'view_class', None) if hasattr(view_class, 'conditional_forward'): app = get_current_app(request) request.matched_rule, request.matched_params = find_rule( request, app) if (request.matched_rule and request.matched_rule.is_forward and request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE')): # We are forwarding the request so the CSRF is delegated # to the application handling the forwarded request. #pylint:disable=protected-access request._dont_enforce_csrf_checks = True LOGGER.debug("dont enforce csrf checks on %s %s", request.method, request.path) auth = get_authorization_header(request).split() if auth and auth[0].lower() in [b'basic', b'bearer']: # We need to support API calls from the command line. #pylint:disable=protected-access request._dont_enforce_csrf_checks = True LOGGER.debug("dont enforce csrf checks on %s %s because"\ " we have an authorization header", request.method, request.path) return super(RulesMiddleware, self).process_view( request, callback, callback_args, callback_kwargs)
def register_by_access_token(request, backend): uri='' strategy = load_strategy(request) backend = load_backend(strategy, backend, uri) # Split by spaces and get the array auth = get_authorization_header(request).split() if not auth: msg= 'No auth provided' return msg if not auth or auth[0].lower() != b'bearer': msg = 'No token header provided.' return msg if len(auth) == 1: msg = 'Invalid token header. No credentials provided.' return msg access_token = auth[1].decode(encoding='UTF-8') user = backend.do_auth(access_token) return user
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)
def authenticate(self, request): """ Perform the actual authentication. Note that the exception raised is always the same. This is so that we don't leak information about in/valid keyIds and other such useful things. """ auth_header = authentication.get_authorization_header(request) if not auth_header or len(auth_header) == 0: return None method, fields = utils.parse_authorization_header(auth_header) # Ignore foreign Authorization headers. if method.lower() != 'signature': return None # Verify basic header structure. if len(fields) == 0: raise FAILED # Ensure all required fields were included. if len(set(("keyid","algorithm","signature")) - set(fields.keys())) > 0: raise FAILED # Fetch the secret associated with the keyid user, secret = self.fetch_user_data( fields["keyid"], algorithm=fields["algorithm"] ) if not (user and secret): raise FAILED # Gather all request headers and translate them as stated in the Django docs: # https://docs.djangoproject.com/en/1.6/ref/request-response/#django.http.HttpRequest.META headers = {} for key in request.META.keys(): if key.startswith("HTTP_") or \ key in ("CONTENT_TYPE", "CONTENT_LENGTH"): header = key[5:].lower().replace('_', '-') headers[header] = request.META[key] # Verify headers hs = HeaderVerifier( headers, secret, required_headers=self.required_headers, method=request.method.lower(), path=request.get_full_path() ) # All of that just to get to this. if not hs.verify(): raise FAILED return (user, fields["keyid"])
def logout(request): auth = get_authorization_header(request).split() try: token = auth[1].decode() except UnicodeError: return cache.delete(token)
def has_permission(self, request, view): token = get_authorization_header(request) if not token: raise AuthenticationFailed() status_code, user = verify_token(token.decode('utf-8')) request.user = user return status_code == 200
def authenticate(self, request): auth_header = get_authorization_header(request).decode().split() if not auth_header or auth_header[0].lower() != self.keyword.lower(): return None access_token = auth_header[1] return self.authenticate_credentials(access_token)
def authenticate(self, request): auth = authentication.get_authorization_header(request).split() if len(auth) != 2 or auth[0] != b'JWT': return None try: payload = self.decode_jwt(auth[1]) user = User.objects.get(username=payload['username']) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return user, payload
def authenticate(self, request): auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'digest': return None if self.authenticator.authenticate(request): return request.user, None else: raise AuthenticationFailed( _(u"Invalid username/password"))
def authenticate(self, request): """ The `authenticate` method is called on every request, regardless of whether the endpoint requires authentication. `authenticate` has two possible return values: 1) `None` - We return `None` if we do not wish to authenticate. Usually this means we know authentication will fail. An example of this is when the request does not include a token in the headers. 2) `(user, token)` - We return a user/token combination when authentication was successful. If neither of these two cases were met, that means there was an error. In the event of an error, we do not return anything. We simple raise the `AuthenticationFailed` exception and let Django REST Framework handle the rest. """ request.user = None # `auth_header` should be an array with two elements: 1) the name of # the authentication header (in this case, "Token") and 2) the JWT # that we should authenticate against. auth_header = authentication.get_authorization_header(request).split() auth_header_prefix = self.authentication_header_prefix.lower() if not auth_header: return None if len(auth_header) == 1: # Invalid token header. No credentials provided. Do not attempt to # authenticate. return None elif len(auth_header) > 2: # Invalid token header. Token string should not contain spaces. Do # not attempt to authenticate. return None # The JWT library we're using can't handle the `byte` type, which is # commonly used by standard libraries in Python 3. To get around this, # we simply have to decode `prefix` and `token`. This does not make for # clean code, but it is a good decision because we would get an error # if we didn't decode these values. prefix = auth_header[0].decode('utf-8') token = auth_header[1].decode('utf-8') if prefix.lower() != auth_header_prefix: # The auth header prefix is not what we expected. Do not attempt to # authenticate. return None # By now, we are sure there is a *chance* that authentication will # succeed. We delegate the actual credentials authentication to the # method below. return self._authenticate_credentials(request, token)
def get_authenticate_header(self, request): auth = get_authorization_header(request).split() if auth and auth[0].lower() == b'token': return TokenAuthentication().authenticate_header(request) if auth and auth[0].lower() == b'temptoken': return TempTokenAuthentication().authenticate_header(request) return super(AuthenticateHeaderMixin, self)\ .get_authenticate_header(request)
def has_permission(self, request, view): auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'key': return None if len(auth) == 1: return False elif len(auth) > 2: return False return auth[1] == settings.PRIVATE_API_KEY
def authenticate(self, request): try: token_type, token_value = get_authorization_header(request).split() return self.authenticate_credentials(token_type, token_value) except UnicodeError: raise exceptions.AuthenticationFailed( _('Invalid token header. ' 'Token string should not contain invalid characters.')) except ValueError: raise exceptions.AuthenticationFailed( _('Invalid token header. ' 'Token string should not be blank'))
def authenticate(self, request): auth = get_authorization_header(request).split() from rest_framework.authentication import exceptions _request = request._request user = getattr(_request, 'user', None) if len(auth) == 2 and auth[0].lower() == b'token' and not user.is_authenticated(): raise exceptions.AuthenticationFailed('Invalid token') return super(TokenSessionAuthentication, self).authenticate(request)
def authenticate(self, request): auth = get_authorization_header(request).decode(HTTP_HEADER_ENCODING).split() if len(auth) == 2 and auth[0].lower() == 'basic': try: payload = jwt.decode(auth[1], settings.SECRET_KEY) username = payload['username'] user = UserBase.objects.get(username__iexact=username) auth_user = User() auth_user.is_active = user.is_activate == 'Y' auth_user.username = user.username if not auth_user.is_active: raise exceptions.AuthenticationFailed(_('User inactive or deleted.')) return auth_user, None except jwt.ExpiredSignatureError: raise exceptions.AuthenticationFailed(_('Expired Signature.')) except jwt.DecodeError: raise exceptions.AuthenticationFailed(_('Signature Decode Failed.')) except UserBase.DoesNotExist: raise exceptions.AuthenticationFailed(_('Invalid username/password.')) return None
def authenticate(self, request): ''' HTTP_AUTHORIZATION': 'Token eyJhbGciOiJIU.eyJpc3MiOiWTy.z0HODSJhWtFzX' try to create user Model from UserModel if suc : return user if falied: return None ''' auth = get_authorization_header(request).split() # 如果未认证, 返回空 if not auth or auth[0].lower() != b'token': return None try: token = auth[1] payload = DecodeJwt().decode_jwt(token) user_id = payload["uid"] user = self.get_user(user_id, payload) except Exception as ex: logger.error(ex) msg = 'Invalid token. auth={0}, error={1}'.format(auth, ex) raise exceptions.AuthenticationFailed(msg) return (user, payload)
def authenticate(self, request): request.user = None auth_header = authentication.get_authorization_header(request).split() auth_header_prefix = self.authentication_header_prefix.lower() if not auth_header: return None if len(auth_header) == 1: return None elif len(auth_header) > 2: return None prefix = auth_header[0].decode('utf-8') token = auth_header[1].decode('utf-8') if prefix.lower() != auth_header_prefix: return None return self._authenticate_credentials(request, token)
def authenticate(self, request): auth = get_authorization_header(request).split() if not auth or auth[0].lower() != self.keyword.lower().encode(): return None if len(auth) == 1 or not auth[1]: return None # This part changed 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) return self.authenticate_credentials(token)
def delete(self, request): auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'token': return Response({"status": "No token provided."}, status=status.HTTP_401_UNAUTHORIZED) if len(auth) == 1: msg = 'Invalid token header. No credentials provided.' return Response({"status": msg}, status=status.HTTP_400_BAD_REQUEST) elif len(auth) > 2: msg = 'Invalid token header. Token string should not contain spaces.' return Response({"status": msg}, status=status.HTTP_400_BAD_REQUEST) # The token was provided, so we are going to delete it try: token = Token.objects.get(key=auth[1]) token.delete() return Response({'status': "Token deleted.".format(auth[1])}) except Token.DoesNotExist: return Response({"status": "Token does not exist."}, status=status.HTTP_401_UNAUTHORIZED)
def authenticate(self, request): auth_header = authentication.get_authorization_header(request) if not auth_header: return None prefix, auth_token = auth_header.decode('utf-8').split(' ') try: payload = jwt.decode(auth_token, settings.SECRET_KEY, 'HS256') user = User.objects.get(phone_number=payload['phone_number']) return user, auth_token except jwt.DecodeError: raise exceptions.AuthenticationFailed('You are unauthorized.') except jwt.ExpiredSignatureError: """ In this case we can build an refresh token guided auth_token issuing process on the client part. """ raise exceptions.AuthenticationFailed( 'Your authorization has expired. Please login again.') return super().authenticate(request)
def authenticate(self, request): auth = get_authorization_header(request).split() if not auth: raise exceptions.AuthenticationFailed( "Authorization header must be supplied.") elif len(auth) == 1: raise exceptions.AuthenticationFailed( 'Invalid token header. No credentials provided.') elif len(auth) > 2: raise exceptions.AuthenticationFailed('Invalid token header') elif auth[0].lower() != b'bearer': raise exceptions.AuthenticationFailed('Invalid token header') try: token = auth[1] if token == self.NULL_TOKEN: raise exceptions.AuthenticationFailed('Null token not allowed') except UnicodeError: raise exceptions.AuthenticationFailed( 'Invalid token header. Token string should not contain invalid ' 'characters.') return self.authenticate_credentials(token)
def authenticate(self, request: HttpRequest) -> Optional[Tuple['User', 'Token']]: auth = get_authorization_header(request).split() if not auth or auth[0].lower() != self.keyword.lower().encode(): return None if len(auth) == 1: msg = 'Invalid token header. No credentials provided.' raise AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid token header. Token string should not contain spaces.' raise AuthenticationFailed(msg) try: token = auth[1].decode() except UnicodeError: msg = 'Invalid token header. Token string should not contain invalid characters.' raise AuthenticationFailed(msg) return self.authenticate_credentials(token)
def get_file_transfer_id(request): auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'filetransfer': msg = _('Invalid filetransfer header. No token header present.') raise exceptions.AuthenticationFailed(msg) if len(auth) == 1: msg = _('Invalid filetransfer header. No credentials provided.') raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = _('Invalid filetransfer header. File transfer id string should not contain spaces.') raise exceptions.AuthenticationFailed(msg) try: file_transfer_id = auth[1].decode() except UnicodeError: msg = _('Invalid filetransfer header. File transfer id string should not contain invalid characters.') raise exceptions.AuthenticationFailed(msg) return file_transfer_id
def authenticate(self, request): auth = get_authorization_header(request).split() ws_uuid = request.resolver_match.kwargs['uuid'] if not auth or auth[0].lower() != self.keyword.lower().encode(): 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) return self.authenticate_credentials(ws_uuid, token)
def authenticate(self, request): token = get_authorization_header(request).split() if token is None or len(token) <= 0: return None if len(token) <= 1: raise exceptions.AuthenticationFailed('인증 형식과 맞지 않습니다.') elif len(token) > 2: raise exceptions.AuthenticationFailed('인증 형식과 맞지 않습니다.') if settings.TOKEN_PREFIX.lower() != smart_text(token[0].lower()): return None try: user = User.objects.get(token=smart_text(token[1])) except ObjectDoesNotExist: raise exceptions.AuthenticationFailed('유효하지 않은 토큰입니다.') request.user = user return (user, None)
def authenticate(self, request): auth = get_authorization_header(request).split() if not auth or auth[0].lower() != self.keyword.lower().encode(): return None if len(auth) == 1: raise AuthenticationFailed( detail='Invalid token header. No credentials provided.') elif len(auth) > 2: raise AuthenticationFailed( detail='Invalid token header.' 'Token string should not contain spaces.') try: token = auth[1].decode() except UnicodeError: raise AuthenticationFailed( detail='Invalid token header.' 'Token string should not contain invalid characters.') return self.authenticate_credentials(token)
def authenticate(self, request): """ Authenticate the request and return a two-tuple of (user, token). """ jwt_value = get_authorization_header(request) if jwt_value is None: return None try: user = jwt.decode(jwt_value, T2TokenViewSet.SECRET, algorithms=[T2TokenViewSet.ALGORITHM]) return (user, jwt_value) except jwt.ExpiredSignature: msg = _('Signature has expired.') raise exceptions.AuthenticationFailed(msg) except jwt.DecodeError: msg = _('Error decoding signature.') raise exceptions.AuthenticationFailed(msg) except jwt.InvalidTokenError: raise exceptions.AuthenticationFailed()
def authenticate(self, request): auth = get_authorization_header(request).split() if not auth: raise exceptions.AuthenticationFailed("Kindly provide the token") if len(auth) == 1 or len(auth) > 2: msg = "Invalid token header." 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) return self.authenticate_credentials(request=request, token=token, ua=request.META.get( 'HTTP_USER_AGENT', b'SYSTEM'))
def authenticate(self, request): provider_url = getattr(settings, 'OAUTH2_PROVIDER_URL', None) if not provider_url: return None provider_url = provider_url.strip('/') auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'bearer': return None if len(auth) == 1: raise exceptions.AuthenticationFailed( 'Invalid token header. No credentials provided.') elif len(auth) > 2: raise exceptions.AuthenticationFailed( 'Invalid token header. Token string should not contain spaces.' ) return self.authenticate_credentials(provider_url, auth[1])
def authenticate(self, request): auth_data = authentication.get_authorization_header(request) if not auth_data: return None prefix, token = auth_data.decode('utf-8').split(' ') try: payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms="HS256") user = User.objects.get(username=payload['username']) return (user, token) except jwt.DecodeError: raise exceptions.AuthenticationFailed( 'Your token is invalid, login') except jwt.ExpiredSignatureError: raise exceptions.AuthenticationFailed( 'Your token is expired, login') return super().authenticate(request)
def get_jwt_value(self, request): auth = get_authorization_header(request).split() if not auth: return None try: prefix, value = auth except ValueError: raise exceptions.AuthenticationFailed( 'Invalid Authorization header.') if force_str(prefix.lower() ) != login_settings.JWT_AUTH_HEADER_PREFIX.lower(): return None if len(auth) != 2: raise exceptions.AuthenticationFailed( 'Invalid Authorization header.') return auth[1]
def patch(self, request): """ Patch api method of notification """ token = get_authorization_header(request).split()[1] payload = jwt.decode(token, SECRET_KEY) user_id = payload['user_id'] list_of_ids = request.data.get('notification_ids') try: self.queryset.filter(id__in=list_of_ids).update(has_read=True) except Exception as err: logger.log_error(str(err)) return api_error_response(message="Something went wrong", status=500) logger.log_info( f"Notification status updated successfully by user_id {user_id}") return api_success_response( message="Notification updated successfully", status=200)
def authenticate(self, request): auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'token': 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) return self.authenticate_credentials(token)
def get_authenticate_header(self, request): """ Determine the WWW-Authenticate header to use for 401 responses. Try to use the request header as an indication for which authentication method was attempted. """ for authenticator in self.get_authenticators(): resp_hdr = authenticator.authenticate_header(request) if not resp_hdr: continue req_hdr = get_authorization_header(request) if not req_hdr: continue if resp_hdr.split()[0] and resp_hdr.split()[0] == req_hdr.split()[0]: return resp_hdr # If it can't be determined from the request, use the last # authenticator (should be Basic). try: return authenticator.authenticate_header(request) except NameError: pass
def authenticate(self, request): set_custom_metric("BearerAuthentication", "Failed") # default value if not self.get_user_info_url(): logger.warning('The setting OAUTH2_USER_INFO_URL is invalid!') set_custom_metric("BearerAuthentication", "NoURL") return None set_custom_metric("BearerAuthentication_user_info_url", self.get_user_info_url()) auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'bearer': set_custom_metric("BearerAuthentication", "None") return None if len(auth) == 1: raise exceptions.AuthenticationFailed('Invalid token header. No credentials provided.') elif len(auth) > 2: raise exceptions.AuthenticationFailed('Invalid token header. Token string should not contain spaces.') output = self.authenticate_credentials(auth[1].decode('utf8')) set_custom_metric("BearerAuthentication", "Success") return output
def authenticate(self, request): self.logger.debug("JWTAuthentication.authenticate") try: token: str = get_authorization_header(request).decode().split()[1] self.logger.debug("Validating token: %s", token) token_resp = self.call_service_method(self.auth_service_name, self.validate_token_method, False, token) self.logger.debug("Token Response: %s", token_resp) if token_resp is not None: return (token_resp, token) else: raise exceptions.AuthenticationFailed() except Exception as ex: self.logger.warning("Authentication failed with error %s", getattr(ex, 'message', repr(ex))) raise exceptions.AuthenticationFailed()
def get_jwt_value(self, request): token = request.query_params.get('token') if token: return token else: auth = get_authorization_header(request).split() auth_header_prefix = api_settings.JWT_AUTH_HEADER_PREFIX.lower() if not auth or smart_text(auth[0].lower()) != auth_header_prefix: return None if len(auth) == 1: msg = _( 'Invalid Authorization header. No credentials provided.') raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = _('Invalid Authorization header. Credentials string ' 'should not contain spaces.') raise exceptions.AuthenticationFailed(msg) return auth[1]
def process_request(self, request): ''' HTTP_AUTHORIZATION': 'Token eyJhbGciOiJIU.eyJpc3MiOiWTy.z0HODSJhWtFzX' ''' auth = get_authorization_header(request).split() # 如果没有token, 返回空 if not auth or auth[0].lower() != b'token': request.META['REMOTE_USER'] = None request.META['payload'] = None return try: token = auth[1] payload = decode_jwt(token) payload["token"] = str(token, encoding='utf-8') user_id = payload["uid"] request.META['REMOTE_USER'] = user_id request.META['payload'] = payload except Exception as ex: logger.error(ex) request.META['REMOTE_USER'] = None request.META['payload'] = None
def authenticate(self, request, simple=False): auth = get_authorization_header(request).split() if not auth and self.allowed_path(request): return self.authenticate_credentials(anonymous=True) if not auth or auth[0].lower() != b'basic': raise AuthenticationFailed('Bad Credentials.') try: auth_parts = base64.b64decode( auth[1]).decode('utf-8').partition(':') except (IndexError, TypeError, base64.binascii.Error): raise AuthenticationFailed('Bad Credentials.') token, password = auth_parts[0], auth_parts[2] payload = self.verify_token(token) return self.authenticate_credentials(payload, password, request=request)
def retrieve(self, request, pk=None): ''' Retrieve Qualifications of logedIn user. endpoints: /api/qualification Method: POST * Login required Returns: List of dictionary having following keys: qualification: qualification name specialization: specialization in which field grade: Grade or Marks from_year: joining year of qualification completion_year: complition year achievement: Any achievement or project or awards. ''' auth_keyword, token = get_authorization_header(self.request).split() user = JWT_DECODE_HANDLER(token).get('user_id', None) queryset = Qualification.objects.filter(user_id=user) serializer = QualificationSerializer(queryset, many=True) return Response(serializer.data)
def authenticate(self, request): print('sadas') rawToken = get_authorization_header(request) print(request.data) print(rawToken) key = 'secretmustbecomplex' jwt_Obj = PyJWT() if not rawToken: return None payload = jwt_Obj.decode(rawToken, key=key) email = payload['email'] password = payload['password'] try: user = UserProfile.objects.get(email=email, password=password) except UserProfile.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None)
def authenticate(self, request): auth = get_authorization_header(request).split() if not auth or auth[0].lower() != self.keyword.lower().encode(): msg = _('Missing Bearer Token') raise exceptions.AuthenticationFailed(msg) if len(auth) == 1: msg = _('Missing Bearer Token') raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = _('Invalid token header. Token string should not contain spaces.') raise exceptions.AuthenticationFailed(msg) receive_token = auth[1] user_id, token, msg = self.parse_token(receive_token) if msg: raise exceptions.AuthenticationFailed(msg) return self.authenticate_credentials(user_id, token, request)
def get_jwt_value(self, request): auth = get_authorization_header(request).split() auth_header_prefix = api_settings.JWT_AUTH_HEADER_PREFIX.lower() if not auth: if api_settings.JWT_AUTH_COOKIE: return request.COOKIES.get(api_settings.JWT_AUTH_COOKIE) return None if smart_text(auth[0].lower()) != auth_header_prefix: return None if len(auth) == 1: msg = _("Invalid Authorization header. No credentials provided.") raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = _("Invalid Authorization header. Credentials string " "should not contain spaces.") raise exceptions.AuthenticationFailed(msg) return auth[1]
def authenticate(self, request): auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'bearer': 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' raise exceptions.AuthenticationFailed(msg) try: token = auth[1] if token == "null": msg = 'Null token not allowed' raise exceptions.AuthenticationFailed(msg) except UnicodeError: msg = 'Invalid token header. Token string should not contain invalid characters.' raise exceptions.AuthenticationFailed(msg) return self.authenticate_credentials(token)