Merge pull request #1453 from nkukard/nkupdates-fix-basic-auth-exception

Basic Auth Exception Handling Improvement
This commit is contained in:
Matt Scott 2023-03-14 19:37:37 -04:00 committed by GitHub
commit 73447d396a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -133,13 +133,24 @@ def api_basic_auth(f):
@wraps(f)
def decorated_function(*args, **kwargs):
auth_header = request.headers.get('Authorization')
if auth_header:
auth_header = auth_header.replace('Basic ', '', 1)
if not auth_header:
current_app.logger.error('Error: Authorization header missing!')
abort(401)
if auth_header[:6] != "Basic ":
current_app.logger.error('Error: Unsupported authorization mechanism!')
abort(401)
# Remove "Basic " from the header value
auth_header = auth_header[6:]
try:
auth_header = str(base64.b64decode(auth_header), 'utf-8')
username, password = auth_header.split(":")
except binascii.Error as e:
# NK: We use auth_components here as we don't know if we'll have a :, we split it maximum 1 times to grab the
# username, the rest of the string would be the password.
auth_components = auth_header.split(':', maxsplit=1)
except (binascii.Error, UnicodeDecodeError) as e:
current_app.logger.error(
'Invalid base64-encoded of credential. Error {0}'.format(
e))
@ -148,6 +159,12 @@ def api_basic_auth(f):
current_app.logger.error('Error: {0}'.format(e))
abort(401)
# If we don't have two auth components (username, password), we can abort
if len(auth_components) != 2:
abort(401)
(username, password) = auth_components
user = User(username=username,
password=password,
plain_text_password=password)
@ -161,8 +178,7 @@ def api_basic_auth(f):
auth_method = request.args.get('auth_method', 'LOCAL')
auth_method = 'LDAP' if auth_method != 'LOCAL' else 'LOCAL'
auth = user.is_validate(method=auth_method,
src_ip=request.remote_addr)
auth = user.is_validate(method=auth_method, src_ip=request.remote_addr)
if not auth:
current_app.logger.error('Checking user password failed')
@ -173,9 +189,6 @@ def api_basic_auth(f):
except Exception as e:
current_app.logger.error('Error: {0}'.format(e))
abort(401)
else:
current_app.logger.error('Error: Authorization header missing!')
abort(401)
return f(*args, **kwargs)