Middlewares: How to apply only to existing routes #49
-
Hey @mathieucarbou, As I’m wrapping up my authentication handler (referenced in this issue), I have a small but important detail that I’m unsure how to handle. I’d like to attach an One approach I considered is attaching it to individual routes rather than the whole server. However, this isn’t ideal, especially when dealing with numerous routes. Another option I thought of is detecting whether To achieve this, I’m considering enumerating all attached handlers. EDIT I would like to be notified of this: ESPAsyncWebServer/src/WebServer.cpp Line 143 in 673431e |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 12 replies
-
In that case, just attach it to the routes: a middleware can be attached globally to the server or to routes.
No, it depends how your app is built. In your case, you would need to have a class that is wrapping the calls and applies the auth middleware depending on the params passed. Something like: static AsyncCallbackWebHandler& secure(const char *uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest) {
return server.on(uri, method, onRequest).addMiddleware(&digestAuth);
} then, just call your secure() method |
Beta Was this translation helpful? Give feedback.
-
@mathieucarbou Is it possible to ask the following as a feature request:The |
Beta Was this translation helpful? Give feedback.
-
@DRSDavidSoft : I have raised a PR here: #50 to:
I added an example showing how to use that: https://github.com/ESP32Async/ESPAsyncWebServer/blob/feat/skip-server-middleware/examples/SkipServerMiddleware/SkipServerMiddleware.ino // we apply auth middleware to the server globally
server.addMiddleware(&basicAuth);
// protected endpoint: requires basic authentication
// curl -v -u admin:admin http://192.168.4.1/
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(200, "text/plain", "Hello, world!");
});
// we skip all global middleware from the catchall handler
server.catchAllHandler().skipServerMiddlewares();
// we apply a specific middleware to the catchall handler only to log requests without a handler defined
server.catchAllHandler().addMiddleware(&logging);
// standard 404 handler: will display the request in the console i na curl-like style
// curl -v -H "Foo: Bar" http://192.168.4.1/foo
server.onNotFound([](AsyncWebServerRequest *request) {
request->send(404, "text/plain", "Not found");
});
|
Beta Was this translation helpful? Give feedback.
@DRSDavidSoft : I have raised a PR here: #50 to:
I added an example showing how to use that: https://github.com/ESP32Async/ESPAsyncWebServer/blob/feat/skip-server-middleware/examples/SkipServerMiddleware/SkipServerMiddleware.ino