Skip to content

Authenticated API Endpoint

In this example, you’ll learn how to protect an API route using a custom authentication middleware. This is useful for securing endpoints that require tokens, API keys, or session headers.


authenticated-api/
β”œβ”€β”€ CMakeLists.txt
β”œβ”€β”€ src/
β”‚ β”œβ”€β”€ main.cpp
β”‚ └── middleware/
β”‚ └── auth.cpp
└── include/
└── middleware/
└── auth.hpp

cmake_minimum_required(VERSION 3.16)
project(authenticated_api)
set(CMAKE_CXX_STANDARD 20)
include(FetchContent)
FetchContent_Declare(
zuno
GIT_REPOSITORY https://github.com/ZunoFramework/zuno.git
GIT_TAG main
)
FetchContent_MakeAvailable(zuno)
include_directories(include)
add_executable(authenticated-api
src/main.cpp
src/middleware/auth.cpp
)
target_link_libraries(authenticated-api PRIVATE zuno)

#include <zuno/zuno.hpp>
#include "middleware/auth.hpp"
int main() {
zuno::App app;
app.get("/public", [](auto& req, auto& res) {
res.send("This is a public endpoint.");
});
app.get("/private", authMiddleware, [](auto& req, auto& res) {
res.send("Access granted to private data.");
});
app.listen(3000);
}

#include &lt;zuno/zuno.hpp&gt;
#include "middleware/auth.hpp"
Middleware authMiddleware = [](auto& req, auto& res, Next next) {
auto auth = req.headers["Authorization"];
if (auth != "Bearer secret-token") {
res.status(401).send("Unauthorized");
return;
}
next(); // Proceed to the route handler
};

#pragma once
#include <zuno/zuno.hpp>
extern Middleware authMiddleware;

Terminal window
curl http://localhost:3000/public
# β†’ This is a public endpoint.
curl http://localhost:3000/private
# β†’ Unauthorized
curl -H "Authorization: Bearer secret-token" http://localhost:3000/private
# β†’ Access granted to private data.


Zuno makes it easy to secure your endpoints with clean, modular middlewareβ€”just like modern frameworks should.