async def basicauth(request: Request): """ X-AWS-Cognito-Username X-AWS-Cognito-Password X-AWS-Cognito-BasicAuth :param request: :return: """ username = request.headers.get('X-AWS-Cognito-Username', None) password = request.headers.get('X-AWS-Cognito-Password', None) if request.headers.get('X-AWS-Cognito-BasicAuth', None): username, password = parse_header( request.headers['X-AWS-Cognito-BasicAuth']) if not username or not password: return response.json({'message': 'username or password not set'}, status=400) authenticator = Authenticator(request.app.nginx_user_cache, client_id=config.client_id, user_salt=app.nginx_user_salt) user = authenticator.auth_basic(username, password) if not user: return response.json({'message': 'authentication failed'}, status=401) request.app.nginx_user_cache[user.username] = user response_headers = { 'X-AWS-Cognito-Username': user.username, 'X-AWS-Cognito-AccessToken': user.access_token, 'X-AWS-Cognito-AttributesJson': json.dumps(user.attributes), } return response.json({'message': 'authorized'}, headers=response_headers, status=200)
def log(self, request, response, time): global setting_dir setting_info = get_setting(setting_dir) port = request.host.split(":")[-1] if (response.status in [401, 403]): try: login, password = parse_header( request.headers["Authorization"]) user = {} user[login] = password # print("暴力破解",request.path_qs, login, password) self.log_message(request.remote, port, "loginFaild", json.dumps(user)) except: pass elif (response.status == 404): filename, file_extension = os.path.splitext(request.path_qs) if (file_extension == ""): # print("目錄猜測",request.path_qs) self.log_message(request.remote, port, "directoryGuess", request.path_qs) else: # print("檔案猜測",request.path_qs) self.log_message(request.remote, port, "fileGuess", request.path_qs) elif (response.status == 200): if ("Authorization" in request.headers and self.check_list( request.path_qs, setting_info['auth_list'])): try: login, password = parse_header( request.headers["Authorization"]) user = {} user[login] = password # print("登入成功",request.path_qs, login,password) self.log_message(request.remote, port, "loginSuccess", json.dumps(user)) except: pass if (self.check_list(request.path_qs, setting_info['sensitives'])): # print("敏感資料",request.path_qs) self.log_message(request.remote, port, "sensitiveFiles", request.path_qs)
def authorize(self, auth_header, auth_fn) -> bool: """""" try: username, password = parse_header(auth_header) except BasicAuthException: username, password = "", "" auth = auth_fn(username, password) if not auth: self.handle_unauthorized_request() return auth
def check_access(auth_dict: dict, header_value: str, strategy: Callable = lambda x: x) -> bool: log.debug('Check access: %r', header_value) try: login, password = parse_header(header_value) except BasicAuthException: return False hashed_password = auth_dict.get(login) hashed_request_password = strategy(password) if hashed_password != hashed_request_password: return False return True
async def status(request): # Chech authorization try: authorization = request.headers.get("Authorization", "") login, password = parse_header(authorization) if login not in request.app[ "users"] or request.app["users"][login] != password: raise BasicAuthException() except BasicAuthException: raise web.HTTPUnauthorized(headers={"WWW-Authenticate": "Basic"}) # Fetch and return data client = request.app["updater"] json_values = { key: [value.value, value.unit] for key, value in client.values.items() } return web.json_response({ "connected": client.connected, "ready": client.ready, "values": json_values })
def get_credentials(self) -> Tuple[str, str]: try: return parse_header(self.header) except BasicAuthException: log.info('Invalid basic auth header: %r', self.header) self.on_error()
def test_header_parse_utf8_default(token, expect): assert parse_header(token) == expect
def test_wrong_header_parse(header): with pytest.raises(BasicAuthException): parse_header(header, coding='utf-8')
def test_header_parse(token, expect): assert parse_header(token, coding='utf-8') == expect