Can I exclude paths from fastapi_oauth2
#25
-
I am trying to do was to define an endpoint that Is there a way to achieve that? I mean, to generate the app with fastapi_oauth2, I setup FastAPI as usual app = FastAPI()
app.include_router(router_ssr)
app.include_router(router_api)
app.include_router(oauth2_router)
app.add_middleware(OAuth2Middleware, config=oauth2_config) I would like to restrict the middleware, to only work on the endpoints Is this possible? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You have to create a wrapper middleware that handles your specific case. I suggest the following: from fastapi import Request
from starlette.datastructures import URL
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.base import RequestResponseEndpoint
from starlette.types import Receive
from starlette.types import Scope
from starlette.types import Send
class SSROAuth2Middleware(BaseHTTPMiddleware):
def __init__(self, app, config, callback):
super().__init__(app)
self.oauth2_middleware = OAuth2Middleware(app, config, callback)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if any(route.path == URL(scope=scope).path for route in router_ssr.routes):
return await self.oauth2_middleware.__call__(scope, receive, send)
await super().__call__(scope, receive, send)
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint):
return await call_next(request) And replace the -app.add_middleware(OAuth2Middleware, config=oauth2_config, callback=on_auth)
+app.add_middleware(SSROAuth2Middleware, config=oauth2_config, callback=on_auth) This will check and skip the middleware if the request path is not acceptable by |
Beta Was this translation helpful? Give feedback.
You have to create a wrapper middleware that handles your specific case. I suggest the following: