def get_jwt_value(self, request): """ Get JWT value from the authorization header API of DRF request object """ raw_auth = get_authorization_header(request) if raw_auth == b'': return None auth = raw_auth.split() auth_header_prefix = 'jwt' 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): # 获取前端传递的token # jwt_value = self.get_jwt_value(request) jwt_token = request.META.get("HTTP_AUTHORIZATION") # 自定义校验规则 token = self.parse_jwt_token(jwt_token) if token is None: return None try: # 将发送过来token反解析出载荷 payload = jwt_decode_handler(token) except jwt.ExpiredSignature: raise exceptions.AuthenticationFailed("签名已过期") except: raise exceptions.AuthenticationFailed("非法用户") # 如果没有任何错误 则将认证出的用户返回 user = self.authenticate_credentials(payload) return user, token
def authenticate_credentials(self, payload): """ Returns an active user that matches the payload's user id and email. """ # User = get_user_model() # User = get_deviceinfo_model() User = DeviceInfo 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 authenticate(self, request): auth_data = authentication.get_authorization_header(request) if auth_data == b'': raise exceptions.AuthenticationFailed( 'Please provide the token,login') token = auth_data.decode('utf-8') try: payload = jwt.decode(token, 'secret') try: user = AdminUser.objects.get(user_id=payload['user']) return (user, token) except AdminUser.DoesNotExist: raise exceptions.AuthenticationFailed( 'Your token is invalid,login') # print(payload) except jwt.DecodeError as identifier: raise exceptions.AuthenticationFailed( 'Your token is invalid,login') except jwt.ExpiredSignatureError as identifier: raise exceptions.AuthenticationFailed( 'Your token is expired,login')
def authenticate(self, request): username = request.META.get( 'X_USERNAME') # get the username request header if not username: # no username passed in request headers return None # authentication did not succeed try: user = UserModel.objects.get( Q(email__iexact=username) | Q(username__iexact=username)) # get the user except User.DoesNotExist: raise exceptions.AuthenticationFailed( 'No such user') # raise exception if user does not exist return (user, None) # authentication successful
def authenticate_scoped_token(token): try: payload = signing.loads( token, salt="scoped_tokens", max_age=settings.SCOPED_TOKENS_MAX_AGE, ) except signing.BadSignature: raise exceptions.AuthenticationFailed("Invalid token signature") try: user_id = int(payload["user_id"]) user_secret = str(payload["user_secret"]) scopes = list(payload["scopes"]) except (KeyError, ValueError, TypeError): raise exceptions.AuthenticationFailed("Invalid scoped token payload") try: user = (models.User.objects.all().for_auth().get( pk=user_id, secret_key=user_secret, is_active=True)) except (models.User.DoesNotExist, ValidationError): raise exceptions.AuthenticationFailed("Invalid user") return user, scopes
def authenticate(self, request): logger = get_logger(__name__) try: incoming_api_key = request.META['HTTP_APIKEY'] except (AttributeError, KeyError): # Missing Authorization Header logger.error( 'authentication_response', response="missing api key", status=status.HTTP_401_UNAUTHORIZED ) logger.debug('authentication_response', response=request, status=status.HTTP_401_UNAUTHORIZED) raise exceptions.AuthenticationFailed('Unauthorised') else: if incoming_api_key != self.api_key: logger.error( 'authentication_response', response="invalid api key", status=status.HTTP_401_UNAUTHORIZED ) raise exceptions.AuthenticationFailed() else: return None, incoming_api_key
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`. """ jwt_value = self.get_jwt_value(request) if jwt_value is None: return None 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() user = self.authenticate_credentials(payload) user_logged_in.send(sender=user.__class__, request=request, user=user) return (user, jwt_value)
def __call__(self, scope): query_dict = {k: v[0] for k, v in parse_qs(scope["query_string"].decode()).items()} jwt_value = query_dict.get('token', None) if jwt_value: try: 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() scope['user'] = self.authenticate_credentials(payload) except exceptions.AuthenticationFailed: scope['user'] = AnonymousUser() return self.inner(scope)
def get_jwt_value(self, request): auth = get_authorization_header(request).split() auth_header_prefix = api_settings.JWT_AUTH_HEADER_PREFIX.lower() # print("type(auth)",type(auth),auth) 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 # print('****************header****************') # print('auth',auth) if auth == [b'JWT']: 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_credentials(self, token): model: AuthToken = self.get_model() msg = _("Invalid token.") stored_tokens = model.objects.filter( Q(key=model.objects.get_key(token)) & (Q(expires__isnull=True) | Q(expires__gt=timezone.now())) ).select_related("user") if not stored_tokens.exists(): raise exceptions.AuthenticationFailed(msg) if not stored_tokens.first().user.is_active: raise exceptions.AuthenticationFailed(_("This user is deactivated!")) for stored_token in stored_tokens.all(): try: digest = model.objects.hash_token(token, stored_token.salt) except (TypeError, binascii.Error): raise exceptions.AuthenticationFailed(msg) if secrets.compare_digest(digest, stored_token.digest): return stored_token.user, stored_token raise exceptions.AuthenticationFailed(msg)
def authenticate(self, request): User = get_user_model() authorization_heaader = request.headers.get('Authorization') if not authorization_heaader: return None try: # header = 'Token xxxxxxxxxxxxxxxxxxxxxxxx' access_token = authorization_heaader.split(' ')[1] payload = jwt.decode( access_token, settings.SECRET_KEY, algorithms=['HS256']) # if token is expired except jwt.ExpiredSignatureError: raise exceptions.AuthenticationFailed( detail={ 'msg': ['Access token expired'], } ) # if token doesn't exist except IndexError: raise exceptions.AuthenticationFailed('Token prefix missing') # get the user associated with the token user = User.objects.filter(id=payload['user_id']).first() if user is None: raise exceptions.AuthenticationFailed('User not found') if not user.is_active: raise exceptions.AuthenticationFailed('user is inactive') # check CSRF Cookie self.enforce_csrf(request) # return the authenticated user object return (user, None)
def authenticate_credentials(self, payload): """ Returns an active user that matches the payload's user id and email. """ id = payload.get('id') if not id: msg = _('Invalid payload.') raise exceptions.AuthenticationFailed(msg) user = get_object_or_none(User, id=id) admin = get_object_or_none(get_user_model(), id=id) if not user and not admin: msg = _('Invalid user.') raise exceptions.AuthenticationFailed(msg) model = user if user else admin if not model.is_active: msg = _('User account is disabled.') raise exceptions.AuthenticationFailed(msg) return model
def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] if not user.is_active: raise exceptions.AuthenticationFailed( _('User inactive or deleted.')) payload = jwt_payload_handler(user) if api_settings.JWT_ALLOW_REFRESH: payload['orig_iat'] = timegm(datetime.utcnow().utctimetuple()) token = jwt_encode_handler(payload) response_data = jwt_response_payload_handler(token, user, request) return Response(response_data, status=status.HTTP_200_OK)
def authenticate(self, request): ret_val = None username = request.META.get('HTTP_X_USERNAME', None) timestamp = request.META.get('HTTP_X_TIMESTAMP', None) client_signature = request.META.get('HTTP_AUTHORIZATION', 'Basic ') client_signature = client_signature.split('Basic ')[1] body = request.body if username and timestamp and client_signature: try: api_user = models.APIUser.objects.get(user__username=username) except models.APIUser.DoesNotExist: raise exceptions.AuthenticationFailed('Incorrect username or ' 'password.') user_timestamp = ro.RedisObject('user_timestamp', username) last_ts = user_timestamp.get() or 0 if last_ts >= float(timestamp): raise exceptions.AuthenticationFailed('Timestamp invalid.') secret = api_user.secret user = api_user.user hasher = hashlib.sha256('{}{}{}{}'.format(username, secret, timestamp, body)) server_signature = hasher.hexdigest() if server_signature != client_signature: raise exceptions.AuthenticationFailed('Incorrect username or ' 'password.') else: user_timestamp.set(float(timestamp)) ret_val = (user, None) return ret_val
def authenticate_credentials(payload): """ Returns an active user that matches the payload's user id and email. """ label = jwt_get_label_from_payload_handler(payload) username = jwt_get_username_from_payload_handler(payload) if label: try: node = Supernodes.objects.get(id=payload.get('id')) except Supernodes.DoesNotExist: msg = _('Invalid signature.') raise exceptions.AuthenticationFailed(msg) return node elif username: try: user = User.objects.get(username=username) except User.DoesNotExist: msg = _('Invalid signature.') raise exceptions.AuthenticationFailed(msg) return user else: msg = _('Invalid payload.') raise exceptions.AuthenticationFailed(msg)
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) user = User.objects.get(username=payload['username']) return (user, token) except jwt.DecodeError as identifier: raise exceptions.AuthenticationFailed( 'Your token is invalid, login') except jwt.ExpiredSignatureError as identifier: raise exceptions.AuthenticationFailed( 'Your token is expired, login') return super().authenticate(request)
def authenticate_token(self, token): try: payload = signing.loads( force_text(token), salt=self.salt, max_age=settings.SESSION_COOKIE_AGE or None, ) except signing.SignatureExpired: msg = { 'detail': ugettext('Signature has expired.'), 'code': 'ERROR_SIGNATURE_EXPIRED', } raise exceptions.AuthenticationFailed(msg) except signing.BadSignature: msg = { 'detail': ugettext('Error decoding signature.'), 'code': 'ERROR_DECODING_SIGNATURE', } raise exceptions.AuthenticationFailed(msg) # We have a valid token, try to find the corresponding user. user = self.authenticate_credentials(payload) return (user, token)
def authenticate_credentials(self, payload): """ Returns a verified AMO user who is active and allowed to make API requests. """ if 'orig_iat' in payload: msg = ("API key based tokens are not refreshable, don't include " "`orig_iat` in their payload.") raise exceptions.AuthenticationFailed(msg) try: api_key = APIKey.get_jwt_key(key=payload['iss']) except APIKey.DoesNotExist: msg = 'Invalid API Key.' raise exceptions.AuthenticationFailed(msg) if api_key.user.deleted: msg = 'User account is disabled.' raise exceptions.AuthenticationFailed(msg) if not api_key.user.read_dev_agreement: msg = 'User has not read developer agreement.' raise exceptions.AuthenticationFailed(msg) core.set_user(api_key.user) return api_key.user
def get_token(self, request): """Extract a bearer token from the HTTP header""" auth = get_authorization_header(request) if not auth: msg = "No authorization header." raise exceptions.AuthenticationFailed(msg) auth = auth.split() len_auth = len(auth) if len_auth == 0: msg = "Empty authorization header." raise exceptions.AuthenticationFailed(msg) elif len_auth == 1: msg = "Invalid bearer header." raise exceptions.AuthenticationFailed(msg) elif len_auth > 2: msg = "Invalid bearer header. Token string must not contain any spaces." raise exceptions.AuthenticationFailed(msg) elif auth[0].lower() != b'bearer': msg = "Invalid bearer header. Missing Bearer." raise exceptions.AuthenticationFailed(msg) return auth[1]
def authenticate(self, request): # 将用户输入的token用变量接收 # token = request._request.GET.get('token') token = request.query_params.get('token') print(token) # 然后在数据库进行匹配 token_obj = models.UserToken.objects.filter(token=token).first() # 如果认证失败 print('token_obj', token_obj) if not token_obj: # 就返回失败 raise exceptions.AuthenticationFailed("用户认证失败") # 在 rest framework内部 会将这两个字段赋值给request,以供后续操作使用 now = int(time.time()) tt = int(token_obj.time) #下面那个是6个小时过期的判断 if now > ( tt + 60 * 60 * 6 ): # 重点就在这句了,这里做了一个Token过期的验证,如果当前的时间大于Token创建时间+DAYS天,那么久返回Token已经过期 raise exceptions.AuthenticationFailed('Token has expired') # 正确就返回用户和token print('token 正确') print(token_obj.user.user_type) #在下面权限认证方面可以找出它的user_type return (token_obj.user, token)
def _authenticate_credentials(self, request, token): """Verifies the access token Return the user details and his access token """ active_user = self._decode_token(token) try: user = User.objects.get(pk=active_user["id"]) except User.DoesNotExist: raise exceptions.AuthenticationFailed( "Invalid user Token, please register an account to acquire valid login credentials." ) return (user, token)
def _authenticate_credentials(self, request, token): """ We will try to authenticate the token. If authentication is successful we return (user, token), otherwise we return an `AuthenticationFailed` error. """ try: payload = jwt.decode(token, settings.SECRET_KEY) except jwt.ExpiredSignatureError: msg = 'Your token has expired, please log in again.' raise exceptions.AuthenticationFailed(msg) except Exception as e: msg = str(e) raise exceptions.AuthenticationFailed(msg) try: user = User.objects.get(pk=payload['id']) except User.DoesNotExist: msg = 'User matching this token was not found.' raise exceptions.AuthenticationFailed(msg) if not user.is_active: msg = 'Forbidden! This user has been deactivated.' raise exceptions.AuthenticationFailed(msg) # active_session = UserDevices.objects.filter(user_id=user.id).first() # if active_session == None: # print("No active session") # uDevice = UserDevices(user=user, token=token) # uDevice.save() # if active_session != None and active_session.token != token: # print("Active session already exists") # raise exceptions.AuthenticationFailed("User session is active on other device") return (user, token)
def authenticate_credentials(self, request, token): """ Authenticate given credentials. If authentication is successful. Return The user and token. If not, return error. """ try: payload = jwt.decode(token, settings.SECRET_KEY) except Exception as e: if e.__class__.__name__ == 'DecodeError': raise exceptions.AuthenticationFailed('Cannot decode token!') elif e.__class__.__name__ == 'ExpiredSignatureError': raise exceptions.AuthenticationFailed('Token has expired!') else: raise exceptions.AuthenticationFailed(str(e)) try: user = User.objects.get(pk=payload['id']) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No user found!') if not user.is_active: raise exceptions.AuthenticationFailed('User has been deactivated!') return user, payload
def get_user(user_id): # Now we know we have a Amsterdam municipal employee (may or may not be allowed acceess) # or external user with access to the `signals` application, we retrieve the Django user. user = cache.get(user_id) if user == USER_DOES_NOT_EXIST: raise exceptions.AuthenticationFailed( USER_NOT_AUTHORIZED.format(user_id)) # We hit the database max once per 5 minutes, and then cache the results. if user is None: # i.e. cache miss try: user = User.objects.get(username__iexact=user_id ) # insensitive match fixes log-in bug except User.DoesNotExist: cache.set(user_id, USER_DOES_NOT_EXIST, 5 * 60) raise exceptions.AuthenticationFailed( USER_NOT_AUTHORIZED.format(user_id)) else: cache.set(user_id, user, 5 * 60) if not user.is_active: raise exceptions.AuthenticationFailed('User inactive') return user
def authenticate(self, request): """ This checks that the passed JWT token is valid Returns: A User's token on successful verification. """ request.user = None # Return Authentication header as a byte string. auth_header = authentication.get_authorization_header(request).split() if not auth_header or auth_header[0].decode().lower( ) != self.keyword.lower(): return None if len(auth_header) == 1: raise exceptions.AuthenticationFailed( 'Invalid token header. No credentials provided!') elif len(auth_header) > 2: raise exceptions.AuthenticationFailed( 'Invalid token header. Token string should not have spaces.') return self.authenticate_credentials(request, auth_header[1].decode())
def authenticate(self, request): res = super().authenticate(request) if not res: return res user, token = res if user.is_admin: sudo = request.META.get('HTTP_SUDO', "") if sudo: target = User.valid_objects.filter(username=sudo).first() if target: return target, token msg = _("Invalid SUDO") raise exceptions.AuthenticationFailed(msg) return user, token
def authenticate(self, request): auth = authentication.get_authorization_header(request).split() if not auth or auth[0].lower() != b'scannertoken': 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: raise exceptions.AuthenticationFailed(self.auth_failed_msg) try: scanner = Scanner.objects.get(token=token) except Scanner.DoesNotExist: raise exceptions.AuthenticationFailed(self.auth_failed_msg) return scanner, token
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 authenticate(self, request): auth = request.META.get('HTTP_AUTHORIZATION', b'') if isinstance(auth, str): auth = auth.encode(HTTP_HEADER_ENCODING) pieces = auth.split() if not pieces or pieces[0].lower() != b'token': return None if len(pieces) == 1: msg = _("Invalid token header. No credentials provided.") raise exceptions.AuthenticationFailed(msg) elif len(pieces) > 2: msg = _("Invalid token header." "Token string should not contain spaces.") raise exceptions.AuthenticationFailed(msg) try: auth = pieces[1].decode() except UnicodeError: msg = _("Invalid token header. " "Token string should not contain invalid characters.") return (AnonymousUser(), auth)