Python falcon.HTTPUnauthorized() Examples

The following are 24 code examples of falcon.HTTPUnauthorized(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module falcon , or try the search function .
Example #1
Source File: backends.py    From falcon-auth with MIT License 6 votes vote down vote up
def parse_auth_token_from_request(self, auth_header):
        """
        Parses and returns the Hawk Authorization header if it is present and well-formed.
        Raises `falcon.HTTPUnauthorized exception` with proper error message
        """
        if not auth_header:
            raise falcon.HTTPUnauthorized(
                description='Missing Authorization Header')

        try:
            auth_header_prefix, _ = auth_header.split(' ', 1)
        except ValueError:
            raise falcon.HTTPUnauthorized(
                description='Invalid Authorization Header: Missing Scheme or Parameters')

        if auth_header_prefix.lower() != self.auth_header_prefix.lower():
            raise falcon.HTTPUnauthorized(
                description='Invalid Authorization Header: '
                            'Must start with {0}'.format(self.auth_header_prefix))

        return auth_header 
Example #2
Source File: __init__.py    From oncall with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _authenticate_user(req):
    session = req.env['beaker.session']
    try:
        req.context['user'] = session['user']

        connection = db.connect()
        cursor = connection.cursor()

        cursor.execute('SELECT `csrf_token` FROM `session` WHERE `id` = %s', session['_id'])
        if cursor.rowcount != 1:
            cursor.close()
            connection.close()
            raise HTTPUnauthorized('Invalid Session', 'CSRF token missing', '')

        token = cursor.fetchone()[0]
        if req.get_header('X-CSRF-TOKEN') != token:
            cursor.close()
            connection.close()
            raise HTTPUnauthorized('Invalid Session', 'CSRF validation failed', '')

        cursor.close()
        connection.close()
    except KeyError:
        raise HTTPUnauthorized('Unauthorized', 'User must be logged in', '') 
Example #3
Source File: bootaction.py    From drydock with Apache License 2.0 6 votes vote down vote up
def check_auth(ba_ctx, req):
        """Check request authentication based on boot action context.

        Raise proper Falcon exception if authentication fails, otherwise
        silently return

        :param ba_ctx: Boot Action context from database
        :param req: The falcon request object of the API call
        """
        identity_key = req.get_header('X-Bootaction-Key', default='')

        if identity_key == '':
            raise falcon.HTTPUnauthorized(
                title='Unauthorized',
                description='No X-Bootaction-Key',
                challenges=['Bootaction-Key'])

        if ba_ctx['identity_key'] != bytes.fromhex(identity_key):
            logger.warn(
                "Forbidding boot action access - node: %s, identity_key: %s, req header: %s"
                % (ba_ctx['node_name'], str(ba_ctx['identity_key']),
                   str(bytes.fromhex(identity_key))))
            raise falcon.HTTPForbidden(
                title='Unauthorized', description='Invalid X-Bootaction-Key') 
Example #4
Source File: db.py    From iris with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def guarded_session():
    '''
    Context manager that will automatically close session on exceptions
    '''
    try:
        session = Session()
        yield session
    except IrisValidationException as e:
        session.close()
        raise HTTPBadRequest('Validation error', str(e))
    except (HTTPForbidden, HTTPUnauthorized, HTTPNotFound, HTTPBadRequest):
        session.close()
        raise
    except Exception:
        session.close()
        logger.exception('SERVER ERROR')
        raise 
Example #5
Source File: authorization.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def authentication_required(req, resp, resource, uri_kwargs):
    """Ensure that user is authenticated otherwise return ``401 Unauthorized``.

    If request fails to authenticate this authorization hook will also
    include list of ``WWW-Athenticate`` challenges.

    Args:
        req (falcon.Request): the request object.
        resp (falcon.Response): the response object.
        resource (object): the resource object.
        uri_kwargs (dict): keyword arguments from the URI template.

    .. versionadded:: 0.4.0
    """
    if 'user' not in req.context:
        args = ["Unauthorized", "This resource requires authentication"]

        # compat: falcon >= 1.0.0 requires the list of challenges
        if FALCON_VERSION >= (1, 0, 0):
            args.append(req.context.get('challenges', []))

        raise HTTPUnauthorized(*args) 
Example #6
Source File: bootaction.py    From drydock with Apache License 2.0 6 votes vote down vote up
def check_auth(ba_ctx, req):
        """Check request authentication based on boot action context.

        Raise proper Falcon exception if authentication fails, otherwise
        silently return

        :param ba_ctx: Boot Action context from database
        :param req: The falcon request object of the API call
        """
        identity_key = req.get_header('X-Bootaction-Key', default='')

        if identity_key == '':
            raise falcon.HTTPUnauthorized(
                title='Unauthorized',
                description='No X-Bootaction-Key',
                challenges=['Bootaction-Key'])

        if ba_ctx['identity_key'] != bytes.fromhex(identity_key):
            logger.warn(
                "Forbidding boot action access - node: %s, identity_key: %s, req header: %s"
                % (ba_ctx['node_name'], str(ba_ctx['identity_key']),
                   str(bytes.fromhex(identity_key))))
            raise falcon.HTTPForbidden(
                title='Unauthorized', description='Invalid X-Bootaction-Key') 
Example #7
Source File: errors_handling.py    From inference-model-manager with Apache License 2.0 6 votes vote down vote up
def default_exception_handler(ex, req, resp, params):
    if hasattr(ex, 'title') and "Failed data validation" in ex.title:
        JsonSchemaException(ex)
    message = "Unexpected error occurred: {}".format(ex)
    logger.error(message + "\nRequest: {}  Params: {}".format(req, params))

    if isinstance(ex, falcon.HTTPUnauthorized):
        raise ex

    if isinstance(ex, falcon.HTTPForbidden):
        raise ex

    stacktrace = traceback.format_exc()
    logger.error(stacktrace)

    raise falcon.HTTPInternalServerError(message) 
Example #8
Source File: helpers.py    From monasca-api with Apache License 2.0 6 votes vote down vote up
def validate_authorization(http_request, authorized_rules_list):
    """Validates whether is authorized according to provided policy rules list.

    If authorization fails, 401 is thrown with appropriate description.
    Additionally response specifies 'WWW-Authenticate' header with 'Token'
    value challenging the client to use different token (the one with
    different set of roles which can access the service).
    """

    challenge = 'Token'
    for rule in authorized_rules_list:
        try:
            http_request.can(rule)
            return
        except Exception as ex:
            LOG.debug(ex)

    raise falcon.HTTPUnauthorized('Forbidden',
                                  'The request does not have access to this service',
                                  challenge) 
Example #9
Source File: backends.py    From falcon-auth with MIT License 6 votes vote down vote up
def _extract_credentials(self, req):
        auth = req.get_header('Authorization')
        token = self.parse_auth_token_from_request(auth_header=auth)
        try:
            token = base64.b64decode(token).decode('utf-8')

        except Exception:
            raise falcon.HTTPUnauthorized(
                description='Invalid Authorization Header: Unable to decode credentials')

        try:
            username, password = token.split(':', 1)
        except ValueError:
            raise falcon.HTTPUnauthorized(
                description='Invalid Authorization: Unable to decode credentials')

        return username, password 
Example #10
Source File: backends.py    From falcon-auth with MIT License 6 votes vote down vote up
def _decode_jwt_token(self, req):

        # Decodes the jwt token into a payload
        auth_header = req.get_header('Authorization')
        token = self.parse_auth_token_from_request(auth_header=auth_header)

        options = dict(('verify_' + claim, True) for claim in self.verify_claims)

        options.update(
            dict(('require_' + claim, True) for claim in self.required_claims)
        )

        try:
            payload = jwt.decode(jwt=token, key=self.secret_key,
                                 options=options,
                                 algorithms=[self.algorithm],
                                 issuer=self.issuer,
                                 audience=self.audience,
                                 leeway=self.leeway)
        except jwt.InvalidTokenError as ex:
            raise falcon.HTTPUnauthorized(
                description=str(ex))

        return payload 
Example #11
Source File: backends.py    From falcon-auth with MIT License 6 votes vote down vote up
def parse_auth_token_from_request(self, auth_header):
        """
        Parses and returns Auth token from the request header. Raises
        `falcon.HTTPUnauthoried exception` with proper error message
        """
        if not auth_header:
            raise falcon.HTTPUnauthorized(
                description='Missing Authorization Header')

        parts = auth_header.split()

        if parts[0].lower() != self.auth_header_prefix.lower():
            raise falcon.HTTPUnauthorized(
                description='Invalid Authorization Header: '
                            'Must start with {0}'.format(self.auth_header_prefix))

        elif len(parts) == 1:
            raise falcon.HTTPUnauthorized(
                description='Invalid Authorization Header: Token Missing')
        elif len(parts) > 2:
            raise falcon.HTTPUnauthorized(
                description='Invalid Authorization Header: Contains extra content')

        return parts[1] 
Example #12
Source File: validation.py    From monasca-log-api with Apache License 2.0 6 votes vote down vote up
def validate_authorization(http_request, authorized_rules_list):
    """Validates whether is authorized according to provided policy rules list.

        If authorization fails, 401 is thrown with appropriate description.
        Additionally response specifies 'WWW-Authenticate' header with 'Token'
        value challenging the client to use different token (the one with
        different set of roles which can access the service).
    """
    challenge = 'Token'
    for rule in authorized_rules_list:
        try:
            http_request.can(rule)
            return
        except Exception as ex:
            LOG.debug(ex)

    raise falcon.HTTPUnauthorized('Forbidden',
                                  'The request does not have access to this service',
                                  challenge) 
Example #13
Source File: authenticate.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def process_request(self, req, resp):

        path = urlparse(req.url)[2]
        if path in self.no_auth_endpoints:
            return

        token = req.get_header('Authorization')

        if token is None:
            raise falcon.HTTPUnauthorized('Auth token required', 'Missing auth token')

        decoded = self.tokenDecoder.decode(token)
        if not decoded:
            logger.info("Failed to decode token")
            raise falcon.HTTPUnauthorized('Authentication required', "Token not valid.")

        if self._token_expired(decoded):
            raise falcon.HTTPUnauthorized('Authentication required', 'Token expired')

        if path in self.admin_endpoints:
            if not self._token_has_admin_priv(decoded):
                raise falcon.HTTPForbidden('Forbidden', "Insufficient permissions")

        if USE_SERVICE_ACCOUNT:
            req.params['Authorization'] = self.sa_token
            logger.info("Using service account token")
        else:
            req.params['Authorization'] = token
        logger.info("Decoded token : {}".format(decoded))
        logger.info("Request path: {}, method {}".format(req.path, req.method)) 
Example #14
Source File: login.py    From oncall with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def on_post(req, resp):
    login_info = uri.parse_query_string(req.context['body'].decode('utf-8'))

    user = login_info.get('username')
    password = login_info.get('password')
    if user is None or password is None:
        raise HTTPBadRequest('Invalid login attempt', 'Missing user/password')

    if not auth_manager.authenticate(user, password):
        raise HTTPUnauthorized('Authentication failure', 'bad login credentials', '')

    connection = db.connect()
    cursor = connection.cursor(db.DictCursor)
    data = get_user_data(None, {'name': user}, dbinfo=(connection, cursor))
    if not data:
        cursor.close()
        connection.close()
        raise HTTPNotFound()

    session = req.env['beaker.session']
    session['user'] = user
    session.save()
    csrf_token = '%x' % SystemRandom().getrandbits(128)
    try:
        cursor.execute('INSERT INTO `session` (`id`, `csrf_token`) VALUES (%s, %s)',
                       (req.env['beaker.session']['_id'], csrf_token))
    except db.IntegrityError:
        raise HTTPBadRequest('Invalid login attempt', 'User already logged in')
    connection.commit()
    cursor.close()
    connection.close()

    # TODO: purge out of date csrf token
    data[0]['csrf_token'] = csrf_token
    resp.body = dumps(data[0]) 
Example #15
Source File: __init__.py    From oncall with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def init(application, config):
    global check_team_auth
    global check_user_auth
    global check_calendar_auth
    global check_calendar_auth_by_id
    global debug_only
    global auth_manager
    global authenticate_user

    if config.get('debug', False):
        def authenticate_user_test_wrapper(req):
            try:
                _authenticate_user(req)
            except HTTPUnauthorized:
                # avoid login for e2e tests
                req.context['user'] = 'test_user'

        logger.info('Auth debug turned on.')
        authenticate_user = authenticate_user_test_wrapper
        check_team_auth = lambda x, y: True
        check_user_auth = lambda x, y: True
        check_calendar_auth = lambda x, y, **kwargs: True
        check_calendar_auth_by_id = lambda x, y: True
        debug_only = lambda function: function

    if config.get('docs') or config.get('require_auth'):
        # Replace login_required decorator with identity function for autodoc generation
        # Also replace if require_auth is True, since AuthMiddleware already handles login for us
        global login_required
        login_required = lambda x: x
    else:
        auth = importlib.import_module(config['module'])
        auth_manager = getattr(auth, 'Authenticator')(config)

    from . import login, logout
    application.add_route('/login', login)
    application.add_route('/logout', logout) 
Example #16
Source File: test_validation.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def test_rule_invalid(self):
        req = mock.Mock()
        req.can = mock_req_can
        test_rules = ['rule1', 'rule2']
        self.assertRaises(
            falcon.HTTPUnauthorized,
            helpers.validate_authorization, req, test_rules) 
Example #17
Source File: token_authenticator.py    From PROTON with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def process_request(self, req, resp):
        """

        :param req:
        :param resp:
        :return:
        """
        # TODO: Validate JWT Token and on success, bind to req object.
        if (req.path in ['/',
                         '/fast-serve',
                         '/signup',
                         '/login',
                         '/reset',
                         '/metrics',
                         '/proton-prom',
                         '/proton-grafana']):
            pass
        elif req.method == 'OPTIONS':
            pass
        else:
            setattr(req.context, 'cache_ready', False)
            challenges = ['Token type="Fernet"']
            token = req.get_header('Authorization')
            if token is None:
                self.logger.exception('[Token Authenticator]: Request to {}[{}] is missing '
                                      'authentication token.'.format(req.path, req.uri))
                raise falcon.HTTPUnauthorized('Auth token required.', 'Please provide an auth token via Authorization '
                                                                      'header; as part of the request.', challenges)
            else:
                if not self.authenticate(token)['status']:
                    self.logger.exception('[Token Authenticator]: Request to {}[{}] has failed '
                                          'authentication. Token - [] is expired/invalid'.format(req.path, req.uri,
                                                                                                 token))
                    raise falcon.HTTPUnauthorized('Authentication required.', 'Token is invalid. Either expired or '
                                                                              'invalid.', challenges)
                else:
                    setattr(req.context, 'cache_ready', True)
                    self.logger.info('[Token Authenticator]: Request to {}[{}] is valid.'.format(req.path, req.uri)) 
Example #18
Source File: __init__.py    From oncall with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def authenticate_application(auth_token, req):
    if not auth_token.startswith('hmac '):
        raise HTTPUnauthorized('Authentication failure', 'Invalid digest format', '')
    method = req.method
    path = req.env['PATH_INFO']
    qs = req.env['QUERY_STRING']
    if qs:
        path = path + '?' + qs
    body = req.context['body'].decode('utf-8')
    try:
        app_name, client_digest = auth_token[5:].split(':', 1)
        connection = db.connect()
        cursor = connection.cursor()
        cursor.execute('SELECT `key` FROM `application` WHERE `name` = %s', app_name)
        if cursor.rowcount > 0:
            api_key = cursor.fetchone()[0].encode('utf-8')
            cursor.close()
            connection.close()
            window = int(time.time()) // 5
            if is_client_digest_valid(client_digest, api_key, window, method, path, body):
                req.context['app'] = app_name
                return
            elif is_client_digest_valid(client_digest, api_key, window - 1, method, path, body):
                req.context['app'] = app_name
                return
            else:
                raise HTTPUnauthorized('Authentication failure', 'Wrong digest', '')
        else:
            cursor.close()
            connection.close()
            raise HTTPUnauthorized('Authentication failure', 'Application not found', '')

    except (ValueError, KeyError):
        raise HTTPUnauthorized('Authentication failure', 'Wrong digest', '') 
Example #19
Source File: backends.py    From falcon-auth with MIT License 5 votes vote down vote up
def authenticate(self, req, resp, resource):
        challenges = []
        for backend in self.backends:
            try:
                user = backend.authenticate(req, resp, resource)
                if user:
                    return user
            except falcon.HTTPUnauthorized as ex:
                www_authenticate = ex.headers.get('WWW-Authenticate')
                if www_authenticate:
                    challenges.append(www_authenticate)

        raise falcon.HTTPUnauthorized(
            description='Authorization Failed',
            challenges=challenges) 
Example #20
Source File: backends.py    From falcon-auth with MIT License 5 votes vote down vote up
def authenticate(self, req, resp, resource):
        request_header = self.parse_auth_token_from_request(req.get_header('Authorization'))

        try:
            # Validate the Authorization header contents and lookup the user's credentials
            # via the provided `credentials_map` function.
            receiver = mohawk.Receiver(
                request_header=request_header,
                method=req.method,
                url=req.forwarded_uri,
                content=req.context.get('body'),
                content_type=req.get_header('Content-Type'),
                **self.receiver_kwargs)
        except mohawk.exc.HawkFail as ex:
            raise falcon.HTTPUnauthorized(
                description='{0}({1!s})'.format(ex.__class__.__name__, ex),
                challenges=(
                    [getattr(ex, 'www_authenticate')]
                    if hasattr(ex, 'www_authenticate')
                    else []))

        # The authentication was successful, get the actual user object now.
        user = self.user_loader(receiver.parsed_header['id'])
        if not user:
            # Should never really happen unless your user objects and their
            # credentials are out of sync.
            raise falcon.HTTPUnauthorized(
                description='Invalid User')

        return user 
Example #21
Source File: backends.py    From falcon-auth with MIT License 5 votes vote down vote up
def authenticate(self, req, resp, resource):
        """
        Extract basic auth token from request `authorization` header,  decode the
        token, verifies the username/password and return either a ``user``
        object if successful else raise an `falcon.HTTPUnauthorized exception`
        """
        username, password = self._extract_credentials(req)
        user = self.user_loader(username, password)
        if not user:
            raise falcon.HTTPUnauthorized(
                description='Invalid Username/Password')

        return user 
Example #22
Source File: backends.py    From falcon-auth with MIT License 5 votes vote down vote up
def authenticate(self, req, resp, resource):
        """
        Extract auth token from request `authorization` header, decode jwt token,
        verify configured claims and return either a ``user``
        object if successful else raise an `falcon.HTTPUnauthorized exception`
        """
        payload = self._decode_jwt_token(req)
        user = self.user_loader(payload)
        if not user:
            raise falcon.HTTPUnauthorized(
                description='Invalid JWT Credentials')

        return user 
Example #23
Source File: app.py    From iris-relay with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def on_post(self, req, resp):
        """
        Accept slack's message from interactive buttons
        """
        try:
            req.context['body'] = req.context['body'].decode('utf-8')
            form_post = falcon.uri.parse_query_string(req.context['body'])
            payload = ujson.loads(form_post['payload'])
            if not self.valid_token(payload['token']):
                logger.error('Invalid token sent in the request.')
                raise falcon.HTTPUnauthorized('Access denied',
                                              'Not a valid auth token')
            try:
                msg_id = int(payload['callback_id'])
            except KeyError as e:
                logger.error(e)
                logger.error('callback_id not found in the json payload.')
                raise falcon.HTTPBadRequest('Bad Request', 'Callback id not found')
            except ValueError as e:
                logger.error(e)
                logger.error('Callback ID not an integer: %s', payload['callback_id'])
                raise falcon.HTTPBadRequest('Bad Request', 'Callback id must be int')
            data = {'msg_id': msg_id,
                    'source': payload['user']['name'],
                    'content': payload['actions'][0]['name']}
            endpoint = self.config['iris']['hook']['slack']
            try:
                result = self.iclient.post(endpoint, data)
            except MaxRetryError as e:
                logger.error(e.reason)
                return
            if result.status == 400:
                raise falcon.HTTPBadRequest('Bad Request', '')
            elif result.status != 200:
                raise falcon.HTTPInternalServerError('Internal Server Error', 'Unknown response from the api')
            else:
                content = process_api_response(result.data)
                self.return_slack_message(resp, content)
            return
        except Exception:
            logger.exception('Unable to read payload from slack. Our post body: %s', req.context['body'])
            raise falcon.HTTPBadRequest('Bad Request', 'Unable to read the payload from slack') 
Example #24
Source File: app.py    From iris-relay with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def on_post(self, req, resp, idp_name):
        saml_client = self.saml_manager.saml_client_for(idp_name)
        req.context['body'] = req.context['body'].decode('utf-8')
        form_data = falcon.uri.parse_query_string(req.context['body'])

        # Pysaml2 defaults to config-defined encryption keys, but must
        # be passed a truthy dict in outstanding_certs in order to
        # do so.
        outstanding = {1: 1}
        authn_response = saml_client.parse_authn_request_response(
            form_data['SAMLResponse'],
            entity.BINDING_HTTP_POST,
            outstanding_certs=outstanding)
        req_id = authn_response.in_response_to
        unsolicited = req_id is None
        subject = authn_response.get_subject()
        username = subject.text
        if self.username_attr:
            username = authn_response.ava[self.username_attr][0]
        refresh_token = hashlib.sha256(os.urandom(32)).hexdigest()
        encrypted_token = self.fernet.encrypt(refresh_token.encode('utf-8'))
        exp = time.time() + self.refresh_ttl
        connection = db.connect()
        cursor = connection.cursor()
        try:
            if not unsolicited:
                cursor.execute('''DELETE FROM `saml_id` WHERE `id` = %s''', req_id)
                if cursor.rowcount == 0:
                    unsolicited = True
            if unsolicited:
                raise falcon.HTTPUnauthorized('Unsolicited request')
            cursor.execute('''INSERT INTO `refresh_token` (`user_id`, `key`, `expiration`)
                              VALUES ((SELECT `id` FROM `target` WHERE `name` = %s AND `type_id` =
                                        (SELECT `id` FROM `target_type` WHERE `name` = 'user')),
                                      %s,
                                      %s)
                              ''',
                           (username, encrypted_token, exp))
            connection.commit()
            key_id = cursor.lastrowid
        finally:
            cursor.close()
            connection.close()
        location = form_data.get('RelayState', self.redirect_url)
        resp.set_header('Location', ''.join([location, '#token=', refresh_token,
                                             '&keyId=', str(key_id), '&expiry=', str(exp),
                                             '&username=', username]))
        resp.status = falcon.HTTP_302