Skip to content

Commit a37d47c

Browse files
committed
Token decode error exception handled
1 parent 61cb20c commit a37d47c

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

backend/services/users/authentication_service.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -70,18 +70,18 @@ def verify_token(token):
7070
class TokenAuthBackend(AuthenticationBackend):
7171
async def authenticate(self, conn):
7272
if "authorization" not in conn.headers:
73-
return
73+
return None
7474

7575
auth = conn.headers["authorization"]
7676
try:
7777
scheme, credentials = auth.split()
7878
if scheme.lower() != "token":
79-
return
79+
return None
8080
try:
8181
decoded_token = base64.b64decode(credentials).decode("ascii")
8282
except UnicodeDecodeError:
8383
logger.debug("Unable to decode token")
84-
return False
84+
return None
8585
except (ValueError, UnicodeDecodeError, binascii.Error):
8686
raise AuthenticationError("Invalid auth credentials")
8787

@@ -90,7 +90,7 @@ async def authenticate(self, conn):
9090
)
9191
if not valid_token:
9292
logger.debug("Token not valid.")
93-
return
93+
return None
9494
tm.authenticated_user_id = user_id
9595
return AuthCredentials(["authenticated"]), SimpleUser(user_id)
9696

@@ -275,7 +275,14 @@ async def login_required_optional(
275275
decoded_token = base64.b64decode(credentials).decode("ascii")
276276
except UnicodeDecodeError:
277277
logger.debug("Unable to decode token")
278-
raise HTTPException(status_code=401, detail="Invalid token")
278+
raise HTTPException(
279+
status_code=status.HTTP_401_UNAUTHORIZED,
280+
detail={
281+
"Error": "Token is expired or invalid",
282+
"SubCode": "InvalidToken",
283+
},
284+
headers={"WWW-Authenticate": "Bearer"},
285+
)
279286
except (ValueError, UnicodeDecodeError, binascii.Error):
280287
raise AuthenticationError("Invalid auth credentials")
281288
valid_token, user_id = AuthenticationService.is_valid_token(decoded_token, 604800)

0 commit comments

Comments
 (0)