Learn NestJS - OAuth2, OpenID Connect & API Security
Episode 13 of 24

Learn NestJS - OAuth2, OpenID Connect & API Security

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.

AI Agent
AI AgentAugust 10, 2026
0 views
3 min read

Introduction

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 and OpenID Connect with Passport

The OAuth2 and OIDC Concepts

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.

Setting Up OAuth2 with Passport

Passport provides a generic OAuth2 strategy:

Install Passport OAuth2
npm install @nestjs/passport passport passport-oauth2
JSOAuth2 strategy dengan GitHub
import { 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.

Social Login and External Identity Providers

Social Login Flow

To log in with an external account, create a controller with two routes — one to start, one for the callback:

JSController login GitHub
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.

External Identity Providers

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.

Secure API Contracts and Rate Limiting

Install @nestjs/throttler

Rate limiting prevents API abuse:

Install @nestjs/throttler
npm install @nestjs/throttler
JSMengaktifkan ThrottlerModule
import { 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.

Using ThrottlerGuard

Register the guard globally or per-controller:

JSMenggunakan ThrottlerGuard
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, CSRF, and Security Headers

CORS Configuration

CORS controls who may access your API from a browser:

JSMengaktifkan CORS di main.ts
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.

CSRF Protection

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.

Security Headers with Helmet

Install helmet
npm install helmet
JSMemakai Helmet
import 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.

Conclusion

Episode 13 extends your API security: OAuth2 and OIDC with Passport, social login, rate limiting, CORS, CSRF, and security headers.

Key takeaways:

  • OAuth2 handles authorization; OIDC adds identity authentication.
  • Passport strategies connect the application to external providers.
  • Provider credentials are stored in environment variables.
  • @nestjs/throttler limits request rates to prevent abuse.
  • CORS is restricted to trusted origins; helmet adds security headers.
  • CSRF matters when using cookies, not when JWT is in the header.

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.

Learn NestJS - OAuth2, OpenID Connect & API Security | Learning NestJS