Skip to content

Guards & JWT

Protect your routes using Guards and built-in JWT support.

Guards

Guards implement the GuardContract and return a boolean (or a Promise of a boolean).

typescript
export class AuthGuard implements GuardContract {
  validate(req: HttpRequest) {
    return req.headers["authorization"] === "secret-token";
  }
}

@Controller("admin")
export class AdminController {
  @Get("secret")
  @Guard(AuthGuard)
  getSecret() {
    return "Top Secret Data";
  }
}

JWT Integration

Bunstone provides a JwtModule and a @Jwt() decorator for easy authentication.

Setup

typescript
@Module({
  imports: [
    JwtModule.register({
      name: "jwt",
      secret: "your-secret-key",
    }),
  ],
})
export class AppModule {}

Usage

typescript
@Controller("profile")
export class ProfileController {
  @Get()
  @Jwt() // Automatically uses the internal JwtGuard
  getProfile(@Request() req: any) {
    return req.jwt.user;
  }
}

Practical Example

Check out a full example using both JWT and custom role-based guards:

ts
import {
  Module,
  Controller,
  Get,
  Jwt,
  Guard,
  AppStartup,
  JwtModule,
} from "../../index";
import type { HttpRequest } from "../../lib/types/http-request";
import type { GuardContract } from "../../lib/interfaces/guard-contract";

class RoleGuard implements GuardContract {
  async validate(req: HttpRequest): Promise<boolean> {
    const role = req.headers["x-role"];
    return role === "admin";
  }
}

@Controller("admin")
class AdminController {
  @Get("secret")
  @Jwt() // Checks for Authorization: Bearer <token>
  @Guard(RoleGuard) // Custom check for x-role: admin
  getSecret() {
    return {
      message: "This is a secret area only for admins with valid JWT!",
    };
  }

  @Get("public")
  getPublic() {
    return { message: "This is public" };
  }
}

@Module({
  imports: [
    JwtModule.register({
      name: "jwt",
      secret: "super-secret-key",
    }),
  ],
  controllers: [AdminController],
})
class AppModule {}

const app = AppStartup.create(AppModule);
app.listen(3000, () => {
  console.log("Guards example is running on http://localhost:3000");
});

See it on GitHub

Released under the MIT License.