This episode covers advanced API security: OAuth2 and OpenID Connect integration with Passport, social login and external identity providers, securing API contracts with rate limiting, and configuring CORS, CSRF, and security headers.

Username and password authentication isn't the only way. Many applications use OAuth2 and OpenID Connect to allow login with Google, GitHub, or enterprise identity provider accounts. Episode 13 covers integrating both and securing your API comprehensively: the OAuth2 flow, social login with Passport, rate limiting, CORS, CSRF, and security headers.
OAuth2 is the standard for authorization — giving an application access to a resource on behalf of a user. OpenID Connect (OIDC) is built on top of OAuth2 and adds an authentication layer — giving the application a verified user identity. Both use flows like the authorization code and token endpoints.
Passport provides a generic OAuth2 strategy:
npm install @nestjs/passport passport passport-oauth2import { Injectable } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { Strategy } from "passport-oauth2";
@Injectable()
export class GithubStrategy extends PassportStrategy(Strategy, "github") {
constructor() {
super({
authorizationURL: "https://github.com/login/oauth/authorize",
tokenURL: "https://github.com/login/oauth/access_token",
clientID: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/github/callback",
});
}
validate(accessToken: string): { accessToken: string } {
return { accessToken };
}
}Secrets like GITHUB_CLIENT_ID are read from the environment via process.env.GITHUB_CLIENT_ID, not hard-coded.
To log in with an external account, create a controller with two routes — one to start, one for the callback:
import { Controller, Get, Req, UseGuards } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
@Controller("auth")
export class AuthController {
@Get("github")
@UseGuards(AuthGuard("github"))
githubLogin(): void {}
@Get("github/callback")
@UseGuards(AuthGuard("github"))
githubCallback(@Req() req): { user: unknown } {
return { user: req.user };
}
}After a successful login, the application usually issues its own JWT for subsequent sessions.
Besides GitHub, many providers are supported: Google (passport-google-oauth20), Facebook, and GitLab. The concept is the same — a Passport strategy with each provider's credentials. For enterprise, identity providers like Okta or Keycloak provide OIDC endpoints that can be used with the passport-openidconnect strategy.
Rate limiting prevents API abuse:
npm install @nestjs/throttlerimport { Module } from "@nestjs/common";
import { ThrottlerModule } from "@nestjs/throttler";
@Module({
imports: [
ThrottlerModule.forRoot([
{
ttl: 60000,
limit: 10,
},
]),
],
})
export class AppModule {}This configuration limits requests to 10 per 60 seconds from a single source.
Register the guard globally or per-controller:
import { Controller, Get, UseGuards } from "@nestjs/common";
import { ThrottlerGuard } from "@nestjs/throttler";
@Controller("api")
@UseGuards(ThrottlerGuard)
export class ApiController {
@Get()
index(): string {
return "API aman";
}
}If the limit is exceeded, the server returns status 429 Too Many Requests.
CORS controls who may access your API from a browser:
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: ["https://app.example.com"],
methods: ["GET", "POST", "PUT", "DELETE"],
credentials: true,
});Restrict origin to known domains, not *, in production.
For applications that use cookies for authentication, CSRF must be prevented. Use a package like csurf or implement a token in the header. If you use JWT in the Authorization header (not cookies), the CSRF risk is much lower because the browser doesn't automatically send that token.
npm install helmetimport helmet from "helmet";
const app = await NestFactory.create(AppModule);
app.use(helmet());Helmet adds important security headers: X-Content-Type-Options, X-Frame-Options, Strict-Transport-Security, and others — protecting against various browser-based attacks.
Episode 13 extends your API security: OAuth2 and OIDC with Passport, social login, rate limiting, CORS, CSRF, and security headers.
Key takeaways:
@nestjs/throttler limits request rates to prevent abuse.In the next episode 14 we'll discuss API gateways and microservices — NestJS microservices architecture, TCP Redis NATS RabbitMQ and Kafka transport layers, gateway patterns and API composition, plus inter-service authentication and message validation.