我们从Python开源项目中,提取了以下3个代码示例,用于说明如何使用falcon.HTTP_401。
def test_401(self, client): client.app.add_route('/401', UnauthorizedResource()) response = client.simulate_request(path='/401') assert response.status == falcon.HTTP_401 assert response.headers['www-authenticate'] == 'Basic realm="simple"' response = client.simulate_post('/401') assert response.status == falcon.HTTP_401 assert response.headers['www-authenticate'] == 'Newauth realm="apps", Basic realm="simple"' response = client.simulate_put('/401') assert response.status == falcon.HTTP_401 assert 'www-authenticate' not in response.headers
def __call__(self, f): @functools.wraps(f) def secure_handler(slf, req, resp, *args, **kwargs): ctx = req.context policy_engine = ctx.policy_engine self.logger.debug("Enforcing policy %s on request %s" % (self.action, ctx.request_id)) if policy_engine is not None and policy_engine.authorize( self.action, ctx): return f(slf, req, resp, *args, **kwargs) else: if ctx.authenticated: slf.info( ctx, "Error - Forbidden access - action: %s" % self.action) slf.return_error( resp, falcon.HTTP_403, message="Forbidden", retry=False) else: slf.info(ctx, "Error - Unauthenticated access") slf.return_error( resp, falcon.HTTP_401, message="Unauthenticated", retry=False) return secure_handler
def __call__(self, f): @functools.wraps(f) def secure_handler(slf, req, resp, *args, **kwargs): ctx = req.context policy_eng = ctx.policy_engine # policy engine must be configured if policy_eng is not None: LOG.debug( 'Enforcing policy %s on request %s using engine %s', self.action, ctx.request_id, policy_eng.__class__.__name__, ctx=ctx) else: LOG.error('No policy engine configured', ctx=ctx) raise ex.PromenadeException( title="Auth is not being handled by any policy engine", status=falcon.HTTP_500, retry=False) authorized = False try: if policy_eng.authorize(self.action, ctx): LOG.debug('Request is authorized', ctx=ctx) authorized = True except Exception: LOG.exception( 'Error authorizing request for action %s', self.action, ctx=ctx) raise ex.ApiError( title="Expectation Failed", status=falcon.HTTP_417, retry=False) if authorized: return f(slf, req, resp, *args, **kwargs) else: # raise the appropriate response exeception if ctx.authenticated: LOG.error( 'Unauthorized access attempted for action %s', self.action, ctx=ctx) raise ex.ApiError( title="Forbidden", status=falcon.HTTP_403, description="Credentials do not permit access", retry=False) else: LOG.error( 'Unathenticated access attempted for action %s', self.action, ctx=ctx) raise ex.ApiError( title="Unauthenticated", status=falcon.HTTP_401, description="Credentials are not established", retry=False) return secure_handler