Authenticated API Endpoint
π Authenticated API Endpoint
Section titled βπ 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.
π§± Project Structure
Section titled βπ§± Project Structureβauthenticated-api/βββ CMakeLists.txtβββ src/β βββ main.cppβ βββ middleware/β βββ auth.cppβββ include/ βββ middleware/ βββ auth.hpp
π CMakeLists.txt
Section titled βπ CMakeLists.txtβcmake_minimum_required(VERSION 3.16)project(authenticated_api)
set(CMAKE_CXX_STANDARD 20)
include(FetchContent)
FetchContent_Declare(zunoGIT_REPOSITORY https://github.com/ZunoFramework/zuno.gitGIT_TAG main)
FetchContent_MakeAvailable(zuno)
include_directories(include)
add_executable(authenticated-apisrc/main.cppsrc/middleware/auth.cpp)
target_link_libraries(authenticated-api PRIVATE zuno)
π src/main.cpp
Section titled βπ src/main.cppβ#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);}
π src/middleware/auth.cpp
Section titled βπ src/middleware/auth.cppβ#include <zuno/zuno.hpp>#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};
π include/middleware/auth.hpp
Section titled βπ include/middleware/auth.hppβ#pragma once#include <zuno/zuno.hpp>
extern Middleware authMiddleware;
π§ͺ Test the API
Section titled βπ§ͺ Test the APIβ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.
π§ Whatβs Next?
Section titled βπ§ Whatβs Next?β- Add Rate Limiting to protect login endpoints
- Use TLS to encrypt credentials
- Return JSON error responses for consistency
Zuno makes it easy to secure your endpoints with clean, modular middlewareβjust like modern frameworks should.