JWT
Simple jwt libs for NHttp.
Install
install external libs @nhttp/jwt
.
- Deno
- deno.land
- npm
- Bun
- Yarn
- pnpm
deno add @nhttp/jwt
import {...} from "https://deno.land/x/nhttp/lib/jwt.ts";
npx jsr add @nhttp/jwt
bunx jsr add @nhttp/jwt
yarn dlx jsr add @nhttp/jwt
pnpm dlx jsr add @nhttp/jwt
Example
import nhttp from "@nhttp/nhttp";
import jwt from "@nhttp/jwt";
// key secret
const JWT_SECRET = "myjwtsecret";
const guard = () => {
return jwt({
secret: JWT_SECRET,
onAuth: (rev, next) => {...}
});
}
const app = nhttp();
app.post("/login", (rev) => {
// example payload.
const payload = {
iat: Math.round(Date.now() / 1000),
// expires 1 hours
exp: Math.round(Date.now() / 1000 + (1 * 60 * 60)),
user: rev.body.username,
};
return { token: jwt.encode(payload, JWT_SECRET) };
});
app.get("/admin/home", guard(), (rev) => {
return `Welcome ${rev.auth.user}`;
});
app.listen(8000, (_err, info) => {
console.log(`Running on port ${info.port}`);
});
With Routing Controller
import { Jwt } from "@nhttp/jwt";
@Controller("/admin")
class AdminController {
...
@Jwt({ secret: "secret" })
@Get("/home")
home(rev: RequestEvent) {
console.log("Payload =>", rev.auth);
return "Welcome Home";
}
...
}