How to use the falcon.HTTPUnauthorized function in falcon

To help you get started, we’ve selected a few falcon examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github falconry / falcon / tests / test_httperror.py View on Github external
def on_get(self, req, resp):
        raise falcon.HTTPUnauthorized('Authentication Required',
                                      'Missing or invalid authorization.',
                                      ['Basic realm="simple"'])
github datalogistics / wildfire-dln / idms / idms / handlers / base.py View on Github external
def do_auth(self, req, resp, resource, params):
        if resource._conf.get('auth', False):
            if not req.auth:
                raise falcon.HTTPMissingHeader("Missing OAuth token", "Authorization")
            
            try:
                bearer, token = req.auth.split()
                assert(bearer == "OAuth")
            except AssertionError as exp:
                raise falcon.HTTPInvalidHeader("Malformed Authorization header", "Authorization")
            
            parts = token.split('.')
            if len(parts) != 3:
                raise falcon.HTTPUnauthorized("Token is not a valid JWT token")
            itok = ".".join(parts[:2])
            sig = hmac.new(resource._conf.get('secret', "there is no secret").encode('utf-8'), itok.encode('utf-8'), digestmod=hashlib.sha256).digest()
            if not hmac.compare_digest(base64.urlsafe_b64encode(sig), parts[2].encode('utf-8')):
                raise falcon.HTTPForbidden()
                
            payload = json.loads(base64.urlsafe_b64decode(parts[1]).decode('utf-8'))
            if payload["exp"] < int(time.time()):
                raise falcon.HTTPForbidden(description="Token has expired")
                
            if not resource.authorize(payload['prv']):
                raise falcon.HTTPForbidden(description="User does not have permission to use this function")
                
            self._usr = payload["iss"]
github laurivosandi / certidude / certidude / auth.py View on Github external
def ldap_authenticate(resource, req, resp, *args, **kwargs):
            """
            Authenticate against LDAP with WWW Basic Auth credentials
            """

            if optional and not req.get_param_as_bool("authenticate"):
                return func(resource, req, resp, *args, **kwargs)

            import ldap

            if not req.auth:
                raise falcon.HTTPUnauthorized("Unauthorized",
                    "No authentication header provided",
                    ("Basic",))

            if not req.auth.startswith("Basic "):
                raise falcon.HTTPBadRequest("Bad request", "Bad header: %s" % req.auth)

            from base64 import b64decode
            basic, token = req.auth.split(" ", 1)
            user, passwd = b64decode(token).decode("ascii").split(":", 1)

            upn = "%s@%s" % (user, const.DOMAIN)
            click.echo("Connecting to %s as %s" % (config.LDAP_AUTHENTICATION_URI, upn))
            conn = ldap.initialize(config.LDAP_AUTHENTICATION_URI, bytes_mode=False)
            conn.set_option(ldap.OPT_REFERRALS, 0)

            try:
github laurivosandi / certidude / certidude / auth.py View on Github external
if not req.auth:
                raise falcon.HTTPUnauthorized("Forbidden", "Please authenticate", ("Basic",))

            if not req.auth.startswith("Basic "):
                raise falcon.HTTPBadRequest("Bad request", "Bad header: %s" % req.auth)

            basic, token = req.auth.split(" ", 1)
            user, passwd = b64decode(token).decode("ascii").split(":", 1)

            import simplepam
            if not simplepam.authenticate(user, passwd, "sshd"):
                logger.critical("Basic authentication failed for user %s from  %s, "
                    "are you sure server process has read access to /etc/shadow?",
                    repr(user), req.context.get("remote_addr"))
                raise falcon.HTTPUnauthorized("Forbidden", "Invalid password", ("Basic",))

            req.context["user"] = User.objects.get(user)
            return func(resource, req, resp, *args, **kwargs)
github netgroup-polito / frog3 / Orchestrator / Orchestrator / ComponentAdapter / OpenstackCommon / authentication.py View on Github external
def ServiceCreateToken(self):
        '''
        @author: Alex Palesandro
        
        Wraps the create token raising an exception if the token is not valid for some reason
        '''
        self.createToken()
        if self.tokendata['access']['token']['id'] is None:              
            raise falcon.HTTPUnauthorized("HTTPUnauthorized", "Token not valid")
        else:
            self.orchToken = self.tokendata['access'][ 'token']['id']
github linkedin / oncall / src / oncall / auth / login.py View on Github external
def on_post(req, resp):
    login_info = uri.parse_query_string(req.context['body'])

    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))
github netgroup-polito / frog3 / Orchestrator / Orchestrator / ComponentAdapter / OpenstackCommon / authentication.py View on Github external
def checkMyToken(self):
        '''
        Return the list of the endpoints of a service
        Args:
            service:
                String that specifies the type of service of the searched endpoints
        '''
        if self.validateToken(self.keystone_server, self.orchToken, self.orchToken) is not True:
            try:
                self.keystone_authentication_url.ServiceCreateToken();
            except:
                raise falcon.HTTPUnauthorized("HTTPUnauthorized", "Token not valid")
github IntelAI / inference-model-manager / management / management_api / authenticate / authenticate.py View on Github external
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")
github laurivosandi / certidude / certidude / api / utils / firewall.py View on Github external
kerberized = False

            if "kerberos" in config.AUTHENTICATION_BACKENDS:
                for subnet in config.KERBEROS_SUBNETS:
                    if req.context.get("remote_addr") in subnet:
                        kerberized = True

            if not req.auth: # no credentials provided
                if optional: # optional allowed
                    req.context["user"] = None
                    return func(resource, req, resp, *args, **kwargs)

                if kerberized:
                    logger.debug("No Kerberos ticket offered while attempting to access %s from %s",
                        req.env["PATH_INFO"], req.context.get("remote_addr"))
                    raise falcon.HTTPUnauthorized("Unauthorized",
                        "No Kerberos ticket offered, are you sure you've logged in with domain user account?",
                        ["Negotiate"])
                else:
                    logger.debug("No credentials offered while attempting to access %s from %s",
                        req.env["PATH_INFO"], req.context.get("remote_addr"))
                    raise falcon.HTTPUnauthorized("Unauthorized", "Please authenticate", ("Basic",))

            if kerberized:
                if not req.auth.startswith("Negotiate "):
                    raise falcon.HTTPUnauthorized("Unauthorized",
                        "Bad header, expected Negotiate",
                        ["Negotiate"])

                os.environ["KRB5_KTNAME"] = config.KERBEROS_KEYTAB

                try:
github netgroup-polito / frog3 / Orchestrator / ServiceLayerApplication / service_layer_application.py View on Github external
except NoResultFound:
            print "EXCEPTION - NoResultFound"
            raise falcon.HTTPNotFound()
        except requests.HTTPError as err:
            logging.exception(err.response.text)
            try:
                if 'code' not in json.loads(err.response.text)['error']:
                    code = json.loads(err.response.text)['code']
                else:
                    code = json.loads(err.response.text)['error']['code']
            except ValueError:
                logging.debug("No json error code")
            else:
                
                if code == 401:
                    raise falcon.HTTPUnauthorized(json.loads(err.response.text)['error']['title'],
                                                  json.loads(err.response.text))
                elif code == 403:
                    raise falcon.HTTPForbidden(json.loads(err.response.text)['error']['title'],
                                                  json.loads(err.response.text)) 
                elif code == 404: 
                    raise falcon.HTTPNotFound()
            raise
        except jsonschema.ValidationError as err:
            logging.exception(err.message)
            raise falcon.HTTPBadRequest('Bad Request',
                                        err.message)
        except ValueError:
            
            logging.exception("Malformed JSON")
            raise falcon.HTTPError(falcon.HTTP_753,
                                   'Malformed JSON',