Để định nghĩa các cơ chế bảo mật nào nên được dùng cho một operation cụ thể, dùng decorator @ApiSecurity().
@ApiSecurity('basic')
@Controller('cats')
export class CatsController {}
Trước khi chạy ứng dụng, hãy nhớ thêm định nghĩa bảo mật vào document nền của bạn bằng DocumentBuilder:
const options = new DocumentBuilder().addSecurity('basic', {
type: 'http',
scheme: 'basic',
});
Một số kỹ thuật xác thực phổ biến nhất đã được tích hợp sẵn (ví dụ basic và bearer), vì vậy bạn không cần định nghĩa cơ chế bảo mật thủ công như trên.
Xác thực Basic (Basic authentication)
Để bật xác thực basic, dùng @ApiBasicAuth().
@ApiBasicAuth()
@Controller('cats')
export class CatsController {}
Trước khi chạy ứng dụng, hãy nhớ thêm định nghĩa bảo mật vào document nền của bạn bằng DocumentBuilder:
const options = new DocumentBuilder().addBasicAuth();
Xác thực Bearer (Bearer authentication)
Để bật xác thực bearer, dùng @ApiBearerAuth().
@ApiBearerAuth()
@Controller('cats')
export class CatsController {}
Trước khi chạy ứng dụng, hãy nhớ thêm định nghĩa bảo mật vào document nền của bạn bằng DocumentBuilder:
const options = new DocumentBuilder().addBearerAuth();
Ghi chú người dịch Ở tầng code, @ApiBearerAuth() chỉ là metadata để Swagger UI hiển thị ô nhập token — nó không tự động validate JWT hay bearer token cho bạn. Việc xác thực thật vẫn phải làm bằng guard riêng (ví dụ AuthGuard với Passport). Nếu bạn từng dùng Express, đây tương đương middleware kiểm tra header Authorization: Bearer ...; decorator này chỉ lo phần “khai báo” cho tài liệu, không lo phần “thực thi”.
Xác thực OAuth2 (OAuth2 authentication)
Để bật OAuth2, dùng @ApiOAuth2().
@ApiOAuth2(['pets:write'])
@Controller('cats')
export class CatsController {}
Trước khi chạy ứng dụng, hãy nhớ thêm định nghĩa bảo mật vào document nền của bạn bằng DocumentBuilder:
const options = new DocumentBuilder().addOAuth2();
Xác thực bằng Cookie (Cookie authentication)
Để bật xác thực bằng cookie, dùng @ApiCookieAuth().
@ApiCookieAuth()
@Controller('cats')
export class CatsController {}
Trước khi chạy ứng dụng, hãy nhớ thêm định nghĩa bảo mật vào document nền của bạn bằng DocumentBuilder:
const options = new DocumentBuilder().addCookieAuth('optional-session-id');