Endpoints need a login
An endpoint that should need a login but answers without one hands your data to anyone who finds the address. API addresses are easy to find: they’re in your app and your website’s code.
- Put the login check in one place that every route passes through (middleware), and make it refuse by default: a route is public only if you mark it public.
- Answer 401 for a missing or invalid login, without any data in the body.
- Mark public endpoints in your OpenAPI file with “security: []”, so the description and the code agree.
Express (Node.js)
// Every route needs a login unless it's listed here
const PUBLIC = new Set(['/health', '/login']);
app.use((req, res, next) => {
if (PUBLIC.has(req.path)) return next();
const user = verifyToken(req.get('Authorization'));
if (!user) return res.status(401).json({ error: 'Login required' });
req.user = user;
next();
});Laravel
// routes/api.php: put every private route inside the auth group
Route::middleware('auth:sanctum')->group(function () {
Route::apiResource('orders', OrderController::class);
});Django REST framework (settings.py)
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.IsAuthenticated'],
}FastAPI
app = FastAPI(dependencies=[Depends(get_current_user)]) # every route needs a login
# public routes go on a separate router without the dependency