Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ libhttpserver is built upon [libmicrohttpd](https://www.gnu.org/software/libmic
- Support for SHOUTcast
- Support for incremental processing of POST data (optional)
- Support for basic and digest authentication (optional)
- Support for centralized authentication with path-based skip rules
- Support for TLS (requires libgnutls, optional)

## Table of Contents
Expand Down Expand Up @@ -990,6 +991,80 @@ You will receive a `SUCCESS` in response (observe the response message from the

You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/digest_authentication.cpp).

### Using Centralized Authentication
The examples above show authentication handled within each resource's `render_*` method. This approach requires duplicating authentication logic in every resource, which is error-prone and violates DRY (Don't Repeat Yourself) principles.

libhttpserver provides a centralized authentication mechanism that runs a single authentication handler before any resource's render method is called. This allows you to:
- Define authentication logic once for all resources
- Automatically protect all endpoints by default
- Specify paths that should bypass authentication (e.g., health checks, public APIs)

```cpp
#include <httpserver.hpp>

using namespace httpserver;

// Resources no longer need authentication logic
class hello_resource : public http_resource {
public:
std::shared_ptr<http_response> render_GET(const http_request&) {
return std::make_shared<string_response>("Hello, authenticated user!", 200, "text/plain");
}
};

class health_resource : public http_resource {
public:
std::shared_ptr<http_response> render_GET(const http_request&) {
return std::make_shared<string_response>("OK", 200, "text/plain");
}
};

// Centralized authentication handler
// Return nullptr to allow the request, or an http_response to reject it
std::shared_ptr<http_response> my_auth_handler(const http_request& req) {
if (req.get_user() != "admin" || req.get_pass() != "secret") {
return std::make_shared<basic_auth_fail_response>("Unauthorized", "MyRealm");
}
return nullptr; // Allow request to proceed to resource
}

int main() {
webserver ws = create_webserver(8080)
.auth_handler(my_auth_handler)
.auth_skip_paths({"/health", "/public/*"});

hello_resource hello;
health_resource health;

ws.register_resource("/api", &hello);
ws.register_resource("/health", &health);

ws.start(true);
return 0;
}
```

The `auth_handler` callback is called for every request before the resource's render method. It receives the `http_request` and can:
- Return `nullptr` to allow the request to proceed normally
- Return an `http_response` (e.g., `basic_auth_fail_response` or `digest_auth_fail_response`) to reject the request

The `auth_skip_paths` method accepts a vector of paths that should bypass authentication:
- Exact matches: `"/health"` matches only `/health`
- Wildcard suffixes: `"/public/*"` matches `/public/`, `/public/info`, `/public/docs/api`, etc.

To test the above example:

# Without auth - returns 401 Unauthorized
curl -v http://localhost:8080/api

# With valid auth - returns 200 OK
curl -u admin:secret http://localhost:8080/api

# Health endpoint (skip path) - works without auth
curl http://localhost:8080/health

You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/centralized_authentication.cpp).

[Back to TOC](#table-of-contents)

## HTTP Utils
Expand Down
88 changes: 88 additions & 0 deletions examples/centralized_authentication.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
This file is part of libhttpserver
Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
*/

#include <memory>
#include <string>

#include <httpserver.hpp>

using httpserver::http_request;
using httpserver::http_response;
using httpserver::http_resource;
using httpserver::webserver;
using httpserver::create_webserver;
using httpserver::string_response;
using httpserver::basic_auth_fail_response;

// Simple resource that doesn't need to handle auth itself
class hello_resource : public http_resource {
public:
std::shared_ptr<http_response> render_GET(const http_request&) {
return std::make_shared<string_response>("Hello, authenticated user!", 200, "text/plain");
}
};

class health_resource : public http_resource {
public:
std::shared_ptr<http_response> render_GET(const http_request&) {
return std::make_shared<string_response>("OK", 200, "text/plain");
}
};

// Centralized authentication handler
// Returns nullptr to allow the request, or an http_response to reject it
std::shared_ptr<http_response> auth_handler(const http_request& req) {
if (req.get_user() != "admin" || req.get_pass() != "secret") {
return std::make_shared<basic_auth_fail_response>("Unauthorized", "MyRealm");
}
return nullptr; // Allow request
}

int main() {
// Create webserver with centralized authentication
// - auth_handler: called before every resource's render method
// - auth_skip_paths: paths that bypass authentication
webserver ws = create_webserver(8080)
.auth_handler(auth_handler)
.auth_skip_paths({"/health", "/public/*"});

hello_resource hello;
health_resource health;

ws.register_resource("/api", &hello);
ws.register_resource("/health", &health);

ws.start(true);

return 0;
}

// Usage:
// # Start the server
// ./centralized_authentication
//
// # Without auth - should get 401 Unauthorized
// curl -v http://localhost:8080/api
//
// # With valid auth - should get 200 OK
// curl -u admin:secret http://localhost:8080/api
//
// # Health endpoint (skip path) - works without auth
// curl http://localhost:8080/health
14 changes: 14 additions & 0 deletions src/httpserver/create_webserver.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
#include <limits>
#include <string>
#include <variant>
#include <vector>

#include "httpserver/http_response.hpp"
#include "httpserver/http_utils.hpp"
Expand All @@ -52,6 +53,7 @@ typedef std::function<std::string(const std::string&)> psk_cred_handler_callback
namespace http { class file_info; }

typedef std::function<bool(const std::string&, const std::string&, const http::file_info&)> file_cleanup_callback_ptr;
typedef std::function<std::shared_ptr<http_response>(const http_request&)> auth_handler_ptr;

class create_webserver {
public:
Expand Down Expand Up @@ -376,6 +378,16 @@ class create_webserver {
return *this;
}

create_webserver& auth_handler(auth_handler_ptr handler) {
_auth_handler = handler;
return *this;
}

create_webserver& auth_skip_paths(const std::vector<std::string>& paths) {
_auth_skip_paths = paths;
return *this;
}

private:
uint16_t _port = DEFAULT_WS_PORT;
http::http_utils::start_method_T _start_method = http::http_utils::INTERNAL_SELECT;
Expand Down Expand Up @@ -423,6 +435,8 @@ class create_webserver {
render_ptr _method_not_allowed_resource = nullptr;
render_ptr _internal_error_resource = nullptr;
file_cleanup_callback_ptr _file_cleanup_callback = nullptr;
auth_handler_ptr _auth_handler = nullptr;
std::vector<std::string> _auth_skip_paths;

friend class webserver;
};
Expand Down
4 changes: 4 additions & 0 deletions src/httpserver/webserver.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
#include <set>
#include <shared_mutex>
#include <string>
#include <vector>

#ifdef HAVE_GNUTLS
#include <gnutls/gnutls.h>
Expand Down Expand Up @@ -182,6 +183,8 @@ class webserver {
const render_ptr method_not_allowed_resource;
const render_ptr internal_error_resource;
const file_cleanup_callback_ptr file_cleanup_callback;
const auth_handler_ptr auth_handler;
const std::vector<std::string> auth_skip_paths;
std::shared_mutex registered_resources_mutex;
std::map<details::http_endpoint, http_resource*> registered_resources;
std::map<std::string, http_resource*> registered_resources_str;
Expand All @@ -197,6 +200,7 @@ class webserver {
std::shared_ptr<http_response> method_not_allowed_page(details::modded_request* mr) const;
std::shared_ptr<http_response> internal_error_page(details::modded_request* mr, bool force_our = false) const;
std::shared_ptr<http_response> not_found_page(details::modded_request* mr) const;
bool should_skip_auth(const std::string& path) const;

static void request_completed(void *cls,
struct MHD_Connection *connection, void **con_cls,
Expand Down
31 changes: 29 additions & 2 deletions src/webserver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,9 @@ webserver::webserver(const create_webserver& params):
not_found_resource(params._not_found_resource),
method_not_allowed_resource(params._method_not_allowed_resource),
internal_error_resource(params._internal_error_resource),
file_cleanup_callback(params._file_cleanup_callback) {
file_cleanup_callback(params._file_cleanup_callback),
auth_handler(params._auth_handler),
auth_skip_paths(params._auth_skip_paths) {
ignore_sigpipe();
pthread_mutex_init(&mutexwait, nullptr);
pthread_cond_init(&mutexcond, nullptr);
Expand Down Expand Up @@ -635,6 +637,19 @@ std::shared_ptr<http_response> webserver::internal_error_page(details::modded_re
}
}

bool webserver::should_skip_auth(const std::string& path) const {
for (const auto& skip_path : auth_skip_paths) {
if (skip_path == path) return true;
// Support wildcard suffix (e.g., "/public/*")
if (skip_path.size() > 2 && skip_path.back() == '*' &&
skip_path[skip_path.size() - 2] == '/') {
std::string prefix = skip_path.substr(0, skip_path.size() - 1);
if (path.compare(0, prefix.size(), prefix) == 0) return true;
}
}
return false;
}

MHD_Result webserver::requests_answer_first_step(MHD_Connection* connection, struct details::modded_request* mr) {
mr->dhr.reset(new http_request(connection, unescaper));
mr->dhr->set_file_cleanup_callback(file_cleanup_callback);
Expand Down Expand Up @@ -747,6 +762,18 @@ MHD_Result webserver::finalize_answer(MHD_Connection* connection, struct details
}
}

// Check centralized authentication if handler is configured
if (found && auth_handler != nullptr) {
std::string path(mr->dhr->get_path());
if (!should_skip_auth(path)) {
std::shared_ptr<http_response> auth_response = auth_handler(*mr->dhr);
if (auth_response != nullptr) {
mr->dhrs = auth_response;
found = false; // Skip resource rendering, go directly to response
}
}
}

if (found) {
try {
if (mr->pp != nullptr) {
Expand Down Expand Up @@ -775,7 +802,7 @@ MHD_Result webserver::finalize_answer(MHD_Connection* connection, struct details
} catch(...) {
mr->dhrs = internal_error_page(mr);
}
} else {
} else if (mr->dhrs == nullptr) {
mr->dhrs = not_found_page(mr);
}

Expand Down
Loading
Loading