JWT (Json Web Token)
@gaman/jwt is a plugin for integrating security based on JSON Web Token (JWT) in the GamanJS framework.
This plugin allows you to easily add token-based authentication.
Install
Section titled “Install”GamanJS is a framework for backend applications. You can install the plugin using your favorite package manager:
npm install @gaman/jwtpnpm install @gaman/jwtyarn install @gaman/jwtbun install @gaman/jwtHow to Use
Section titled “How to Use”Here is an example of implementing @gaman/jwt in a GamanJS application:
import { jwt } from "@gaman/jwt"
defineBootstrap((app) => { app.mount( jwt({ secret: 'secret', header: 'Authorization', required: false, includes: ['/jwt/unprotected', '/jwt/token'], }), jwt({ secret: 'secret', header: 'Authorization', required: true, includes: ['/jwt/protected'], excludes: ['/jwt/unprotected', '/jwt/token'], }), ); // mount other routes here})The code above results in:
-
/jwt/unprotectedand/jwt/tokennot protected (free access) -
/jwt/protectedprotected and requires headerAuthorizationcontaining a valid token
Creating Controller for Login
Section titled “Creating Controller for Login”To create login endpoint and JWT testing, you can create a controller like this:
import { composeController, Res } from "@gaman/core"
export default composeController(() => ({ // endpoint for generating token Token: async (ctx) => { const { username, password } = await ctx.req.json() // simple validation if (username !== "admin" || password !== "123456") { return Res.json({ message: "invalid credentials" }, { status: 401 }) } const token = ctx.jwt.sign({ user: { username } }, { secret: "secret", expiresIn: "1h" }) return Res.json({ token }) }, // protected endpoint Protected: (ctx) => { return Res.json({ message: "Access granted", user: ctx.jwt?.user, }) }, // free access endpoint Unprotected: () => { return Res.json({ message: "Public route" }) },}))Register Controller to Router
Section titled “Register Controller to Router”Add the controller in your routing:
import { autoComposeRoutes } from "@gaman/core"import { JwtController } from "../controllers/JwtController.ts"
export default autoComposeRoutes((route) => { route.group("/jwt", (route) => { route.post("/token", [JwtController, "Token"]) route.get("/protected", [JwtController, "Protected"]) route.get("/unprotected", [JwtController, "Unprotected"]) })})Testing
Section titled “Testing”-
Send
POST /jwt/tokenwith body:{"username": "admin","password": "123456"}will return JWT token.
-
Use token in header:
Authorization: Bearer <token> -
Access
/jwt/protected→ will display user data from token. -
Access
/jwt/unprotected→ can be accessed without token.