Auth Package
Auth Middleware
Protect routes with JWT authentication middleware.
Auth Middleware
Protect routes with JWT authentication middleware.
Basic Usage
import { authMiddleware } from "@lara-node/auth";
Route.get("/profile", UserController.profile).middleware("auth");
How It Works
The middleware:
- Extracts the
Bearertoken fromAuthorizationheader - Verifies the token
- Sets
req.userwith the decoded payload - Returns 401 if token is invalid or missing
Accessing User
@Route.get('/profile')
async profile(req: Request) {
// req.user contains the decoded token payload
const userId = req.user.userId
return User.find(userId)
}
With User Loader
Load the full user model:
// In middleware configuration
{
auth: {
middleware: AuthMiddleware,
options: {
userLoader: async (payload) => {
return User.find(payload.userId)
}
}
}
}
Then access the full user:
@Route.get('/profile')
async profile(req: Request) {
return req.user // Full User model
}
Registering the Middleware
export class MiddlewareProvider extends MiddlewareServiceProvider {
registerMiddleware() {
return {
aliases: {
auth: AuthMiddleware,
},
groups: {
api: ["auth", "throttle"],
},
};
}
}
Next Steps
- Token Generation -- JWT tokens
- Password Hashing -- Hash passwords
- Built-in Middleware -- All middleware