本文整理匯總了Python中falcon.HTTPUnauthorized方法的典型用法代碼示例。如果您正苦於以下問題:Python falcon.HTTPUnauthorized方法的具體用法?Python falcon.HTTPUnauthorized怎麽用?Python falcon.HTTPUnauthorized使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類falcon
的用法示例。
在下文中一共展示了falcon.HTTPUnauthorized方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: check_auth
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPUnauthorized [as 別名]
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')
示例2: parse_auth_token_from_request
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPUnauthorized [as 別名]
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]
示例3: _decode_jwt_token
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPUnauthorized [as 別名]
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
示例4: _extract_credentials
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPUnauthorized [as 別名]
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
示例5: default_exception_handler
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPUnauthorized [as 別名]
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)
示例6: authentication_required
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPUnauthorized [as 別名]
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)
示例7: guarded_session
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPUnauthorized [as 別名]
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
示例8: _authenticate_user
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPUnauthorized [as 別名]
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', '')
示例9: validate_authorization
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPUnauthorized [as 別名]
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)
示例10: validate_authorization
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPUnauthorized [as 別名]
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)
示例11: authenticate
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPUnauthorized [as 別名]
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
示例12: process_request
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPUnauthorized [as 別名]
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))
示例13: authenticate_application
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPUnauthorized [as 別名]
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', '')
示例14: init
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPUnauthorized [as 別名]
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)
示例15: on_post
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPUnauthorized [as 別名]
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])