Skip to content

Commit aa8f4b3

Browse files
committed
GH-22: Handle the authentication exceptions in the middleware
1 parent 2a23ede commit aa8f4b3

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

src/fastapi_oauth2/middleware.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,15 @@
1010
from typing import Union
1111

1212
from fastapi.security.utils import get_authorization_scheme_param
13+
from jose.exceptions import JOSEError
1314
from jose.jwt import decode as jwt_decode
1415
from jose.jwt import encode as jwt_encode
1516
from starlette.authentication import AuthCredentials
1617
from starlette.authentication import AuthenticationBackend
1718
from starlette.authentication import BaseUser
1819
from starlette.middleware.authentication import AuthenticationMiddleware
1920
from starlette.requests import Request
21+
from starlette.responses import PlainTextResponse
2022
from starlette.types import ASGIApp
2123
from starlette.types import Receive
2224
from starlette.types import Scope
@@ -144,5 +146,9 @@ def __init__(
144146

145147
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
146148
if scope["type"] == "http":
147-
return await self.auth_middleware(scope, receive, send)
149+
try:
150+
return await self.auth_middleware(scope, receive, send)
151+
except (JOSEError, Exception) as e:
152+
middleware = PlainTextResponse(str(e), status_code=401)
153+
return await middleware(scope, receive, send)
148154
await self.default_application_middleware(scope, receive, send)

0 commit comments

Comments
 (0)