Giter Club home page Giter Club logo

Comments (8)

Goldziher avatar Goldziher commented on May 23, 2024

Middleware are always called, also in Starlette. Why shouldn't they run for an Options request?

As for the order of middlewares, this is the pertinent code:

    def build_middleware_stack(
        self,
        user_middleware: List[Union[Middleware, Type[BaseHTTPMiddleware], Type[MiddlewareProtocol]]],
        allowed_hosts: Optional[List[str]],
        cors_config: Optional[CORSConfig],
    ) -> ASGIApp:
        """
        Builds the middleware stack by passing middlewares in a specific order
        """
        current_app: ASGIApp = self.asgi_router
        if allowed_hosts:
            current_app = TrustedHostMiddleware(app=current_app, allowed_hosts=allowed_hosts)
        if cors_config:
            current_app = CORSMiddleware(app=current_app, **cors_config.dict())
        for middleware in user_middleware:
            if isinstance(middleware, Middleware):
                current_app = middleware.cls(app=current_app, **middleware.options)
            else:
                current_app = middleware(app=current_app)
        return current_app

from litestar.

slavugan avatar slavugan commented on May 23, 2024

See my log, for Options request TrustedHostMiddleware is not called, because CORSMiddleware returns response.
For example what is the sense to run auth middleware for Options request or before host check?

from litestar.

slavugan avatar slavugan commented on May 23, 2024

Look how Starlette calls middlewares

///server error middleware called
///cors middleware called
INFO:     127.0.0.1:53186 - "OPTIONS /api/a/brands HTTP/1.1" 200 OK
# here OPTIONS ends and POST starts
///server error middleware called
///cors middleware called
///trusted host middleware called///
////some middleware called
////some middleware2 called
///exception middleware called
INFO:     127.0.0.1:53186 - "POST /api/a/brands HTTP/1.1" 405 Method Not Allowed

and Starlette app

async def brand(request):
    return JSONResponse({'hello': 'brand'})

class SomeMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        print('////some middleware called')
        return await call_next(request)
        print('////some middleware awaited')

middlewares = [
    Middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], allow_methods=('GET', 'POST')),
    Middleware(TrustedHostMiddleware, allowed_hosts=['localhost']),
    Middleware(SomeMiddleware),
    Middleware(SomeMiddleware2),
]

app = Starlette(
    debug=True,
    middleware=middlewares,
    routes=[
        Route('/api/a/brands', brand),
    ]
)

Also Starlette provide ExceptionMiddleware where I can catch validation errors and not break CORSMiddleware

from litestar.

Goldziher avatar Goldziher commented on May 23, 2024

Lets keep this thread ordered.

  1. You are saying the order of middlewares is incorrect, and the logging you posted above appears to support this. The simplest course of action I can suggest is that you submit a PR. Either with a fix for the issue if you identify it, or with a failing test case that demonstrates this, use the @xfail decorator so the test actually passes.
  2. The starlette app you created has a different order of middlewares than the one baked into Starlite. Starlite, as you can see in the code snippet I posted previously, places trusted hosts before the CORSMiddleware. There is nothing stopping you from using the Starlette CORSMiddleware and/or TrustedHostMiddleware on your own and not use the builtin Starlite configurations. Is there an issue doing this? If you think that CORSMiddleware shoulds be called before the TrustedHostMiddleware, please give me a compelling reason why this is so. Its not a big adjustment to do.

from litestar.

slavugan avatar slavugan commented on May 23, 2024

Despite the fact that in Starlie TrustedHostMiddleware is placed before the CORSMiddleware, as you can see in my log for Starlite CORSMiddleware is called first. But for these two middlewares any order is fine I think. As TrustedHostMiddleware does not return any useful data in the body.
But if some middleware returns data in the body which client app needs to read it is important to call this middleware after CORSMiddleware

from litestar.

slavugan avatar slavugan commented on May 23, 2024

Added PR #105

from litestar.

Goldziher avatar Goldziher commented on May 23, 2024

Thanks for your contribution! v1.3.0 has been released with your fixes.

from litestar.

slavugan avatar slavugan commented on May 23, 2024

Great! Thanks.

from litestar.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.