🔒 Security

OIDC

OpenID Connect

An authentication layer built on top of the OAuth 2.0 protocol. It answers the question "Who are you?" and securely conveys user identity information through an ID Token in JWT (JSON Web Token) format. It is the de facto standard for modern social logins such as Google, Microsoft, and Apple sign-in, and for SSO, and was approved as an international standard in 2024 as ISO/IEC 26131:2024.

📖 Detailed Explanation

OIDC (OpenID Connect) solves the "authentication" problem that OAuth 2.0 does not address. OAuth 2.0 focuses only on "Is this app allowed to access my data?" (authorization), but does not deal with "Who is this user?" (authentication). OIDC adds a JWT called the ID Token to the OAuth 2.0 flow to deliver the user's identity to the client. For example, when you click "Sign in with Google," OIDC operates and tells the app your email and name.

OIDC has three core components. The ID Token is a JWT containing the user's identity, including claims such as the issuer (iss), audience (aud), subject (sub), and expiration time (exp). The UserInfo endpoint is where you access additional user information (profile photo, phone number, etc.) using the Access Token. The Discovery Document (.well-known/openid-configuration) automatically tells the client all of the IdP's endpoints and supported features, simplifying client configuration. Thanks to this developer-friendly design, those with OAuth 2.0 experience can adopt OIDC easily.

The OIDC authentication flow is chosen according to the application type. Authorization Code Flow (+ PKCE) is the standard for web apps and mobile apps, and is the safest method, exchanging a code for tokens. Implicit Flow is no longer recommended, as it carries the risk of tokens being exposed in the browser. Hybrid Flow receives some tokens through the front channel and the rest through the back channel, providing flexibility. As of 2025, PKCE is mandatory for all public clients (SPAs, mobile apps).

OIDC has also brought innovation to CI/CD pipelines. GitHub Actions uses OIDC to authenticate to AWS, GCP, and Azure without passwords. When a workflow runs, GitHub issues a JWT, and the cloud provider verifies the claims in this token (repository, branch, environment) to grant permissions. This eliminates the risk of storing long-lived credentials in code and automates the principle of least privilege. Across modern infrastructure, including Kubernetes and HashiCorp Vault, OIDC-based workload identity is becoming the standard.

💻 Code Example

// OIDC ID Token 검증 예제 - Node.js
const jwt = require('jsonwebtoken');
const jwksClient = require('jwks-rsa');
const axios = require('axios');

// OIDC 프로바이더 설정
const ISSUER = 'https://accounts.google.com';
const CLIENT_ID = process.env.GOOGLE_CLIENT_ID;

// Discovery Document에서 JWKS URI 가져오기
async function getJwksUri(issuer) {
    const discoveryUrl = `${issuer}/.well-known/openid-configuration`;
    const response = await axios.get(discoveryUrl);

    console.log('OIDC Discovery Document:', {
        issuer: response.data.issuer,
        authorization_endpoint: response.data.authorization_endpoint,
        token_endpoint: response.data.token_endpoint,
        userinfo_endpoint: response.data.userinfo_endpoint,
        jwks_uri: response.data.jwks_uri,
    });

    return response.data.jwks_uri;
}

// JWKS 클라이언트 생성 (키 캐싱 포함)
let client;
async function initJwksClient() {
    const jwksUri = await getJwksUri(ISSUER);
    client = jwksClient({
        jwksUri,
        cache: true,           // 키 캐싱 활성화
        cacheMaxEntries: 5,    // 최대 5개 키 캐시
        cacheMaxAge: 600000,   // 10분 캐시
        rateLimit: true,       // 요청 제한
        jwksRequestsPerMinute: 10,
    });
}

// kid로 공개키 가져오기
function getSigningKey(kid) {
    return new Promise((resolve, reject) => {
        client.getSigningKey(kid, (err, key) => {
            if (err) return reject(err);
            resolve(key.getPublicKey());
        });
    });
}

// ID Token 검증 함수
async function verifyIdToken(idToken) {
    // 1. 토큰 디코딩 (검증 전)
    const decoded = jwt.decode(idToken, { complete: true });
    if (!decoded) {
        throw new Error('Invalid token format');
    }

    console.log('Token Header:', decoded.header);
    console.log('Token Payload:', decoded.payload);

    // 2. 헤더에서 알고리즘과 키 ID 확인
    const { alg, kid } = decoded.header;
    if (alg !== 'RS256') {
        throw new Error(`Unsupported algorithm: ${alg}`);
    }

    // 3. JWKS에서 공개키 가져오기
    const publicKey = await getSigningKey(kid);

    // 4. 토큰 검증 (서명, 만료, 발급자, 대상)
    const verified = jwt.verify(idToken, publicKey, {
        algorithms: ['RS256'],
        issuer: ISSUER,
        audience: CLIENT_ID,
        clockTolerance: 5,  // 5초 오차 허용
    });

    // 5. 추가 클레임 검증
    // nonce 검증 (CSRF 방지 - 세션에 저장된 값과 비교)
    // if (verified.nonce !== sessionNonce) throw new Error('Invalid nonce');

    // at_hash 검증 (Access Token 바인딩)
    // 생략: access_token의 해시가 at_hash와 일치하는지 확인

    return {
        sub: verified.sub,          // 사용자 고유 식별자
        email: verified.email,
        emailVerified: verified.email_verified,
        name: verified.name,
        picture: verified.picture,
        issuedAt: new Date(verified.iat * 1000),
        expiresAt: new Date(verified.exp * 1000),
    };
}

// 사용 예시
async function main() {
    await initJwksClient();

    const idToken = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ii4uLiJ9...';

    try {
        const user = await verifyIdToken(idToken);
        console.log('Verified user:', user);
    } catch (error) {
        console.error('Token verification failed:', error.message);
    }
}

// Express 미들웨어로 사용
function oidcAuth(req, res, next) {
    const authHeader = req.headers.authorization;
    if (!authHeader?.startsWith('Bearer ')) {
        return res.status(401).json({ error: 'Missing token' });
    }

    const token = authHeader.substring(7);
    verifyIdToken(token)
        .then(user => {
            req.user = user;
            next();
        })
        .catch(err => {
            res.status(401).json({ error: err.message });
        });
}
# OIDC Authorization Code Flow + PKCE 구현 - Python (FastAPI)
import secrets
import hashlib
import base64
from urllib.parse import urlencode
import httpx
from jose import jwt, JWTError
from jose.exceptions import ExpiredSignatureError
from fastapi import FastAPI, Request, HTTPException, Depends
from fastapi.responses import RedirectResponse
from pydantic import BaseModel

app = FastAPI()

# OIDC 설정
OIDC_CONFIG = {
    "issuer": "https://accounts.google.com",
    "client_id": "your-client-id",
    "client_secret": "your-client-secret",
    "redirect_uri": "http://localhost:8000/callback",
    "scopes": ["openid", "profile", "email"],
}

# 세션 저장소 (실제로는 Redis 등 사용)
sessions = {}


def generate_pkce():
    """PKCE code_verifier와 code_challenge 생성"""
    # 1. code_verifier: 43-128자의 랜덤 문자열
    code_verifier = secrets.token_urlsafe(64)

    # 2. code_challenge: code_verifier의 SHA256 해시를 Base64 URL 인코딩
    digest = hashlib.sha256(code_verifier.encode()).digest()
    code_challenge = base64.urlsafe_b64encode(digest).rstrip(b'=').decode()

    return code_verifier, code_challenge


async def get_oidc_config(issuer: str):
    """Discovery Document에서 OIDC 설정 가져오기"""
    async with httpx.AsyncClient() as client:
        response = await client.get(
            f"{issuer}/.well-known/openid-configuration"
        )
        return response.json()


async def get_jwks(jwks_uri: str):
    """JWKS(공개키 세트) 가져오기"""
    async with httpx.AsyncClient() as client:
        response = await client.get(jwks_uri)
        return response.json()


@app.get("/login")
async def login(request: Request):
    """로그인 시작 - IdP로 리다이렉트"""
    # PKCE 생성
    code_verifier, code_challenge = generate_pkce()

    # state (CSRF 방지)
    state = secrets.token_urlsafe(32)

    # nonce (리플레이 공격 방지)
    nonce = secrets.token_urlsafe(32)

    # 세션에 저장 (토큰 교환 시 검증용)
    session_id = secrets.token_urlsafe(16)
    sessions[session_id] = {
        "code_verifier": code_verifier,
        "state": state,
        "nonce": nonce,
    }

    # OIDC 설정 가져오기
    oidc_config = await get_oidc_config(OIDC_CONFIG["issuer"])

    # Authorization URL 구성
    params = {
        "client_id": OIDC_CONFIG["client_id"],
        "response_type": "code",
        "scope": " ".join(OIDC_CONFIG["scopes"]),
        "redirect_uri": OIDC_CONFIG["redirect_uri"],
        "state": state,
        "nonce": nonce,
        "code_challenge": code_challenge,
        "code_challenge_method": "S256",  # PKCE 필수
    }

    auth_url = f"{oidc_config['authorization_endpoint']}?{urlencode(params)}"

    response = RedirectResponse(url=auth_url)
    response.set_cookie("oidc_session", session_id, httponly=True, secure=True)
    return response


@app.get("/callback")
async def callback(request: Request, code: str, state: str):
    """IdP로부터 콜백 처리"""
    # 세션 확인
    session_id = request.cookies.get("oidc_session")
    if not session_id or session_id not in sessions:
        raise HTTPException(400, "Invalid session")

    session_data = sessions[session_id]

    # state 검증 (CSRF 방지)
    if state != session_data["state"]:
        raise HTTPException(400, "Invalid state")

    # OIDC 설정 가져오기
    oidc_config = await get_oidc_config(OIDC_CONFIG["issuer"])

    # Authorization Code를 토큰으로 교환
    async with httpx.AsyncClient() as client:
        token_response = await client.post(
            oidc_config["token_endpoint"],
            data={
                "grant_type": "authorization_code",
                "code": code,
                "redirect_uri": OIDC_CONFIG["redirect_uri"],
                "client_id": OIDC_CONFIG["client_id"],
                "client_secret": OIDC_CONFIG["client_secret"],
                "code_verifier": session_data["code_verifier"],  # PKCE
            },
        )

    if token_response.status_code != 200:
        raise HTTPException(400, f"Token exchange failed: {token_response.text}")

    tokens = token_response.json()
    id_token = tokens["id_token"]
    access_token = tokens["access_token"]

    # ID Token 검증
    jwks = await get_jwks(oidc_config["jwks_uri"])

    try:
        # JWT 검증 (서명, 만료, 발급자, 대상)
        claims = jwt.decode(
            id_token,
            jwks,
            algorithms=["RS256"],
            audience=OIDC_CONFIG["client_id"],
            issuer=OIDC_CONFIG["issuer"],
        )

        # nonce 검증 (리플레이 공격 방지)
        if claims.get("nonce") != session_data["nonce"]:
            raise HTTPException(400, "Invalid nonce")

    except ExpiredSignatureError:
        raise HTTPException(401, "Token expired")
    except JWTError as e:
        raise HTTPException(401, f"Token validation failed: {str(e)}")

    # 세션 정리
    del sessions[session_id]

    # 사용자 정보 반환 (실제로는 세션 생성)
    return {
        "user": {
            "sub": claims["sub"],
            "email": claims.get("email"),
            "name": claims.get("name"),
            "picture": claims.get("picture"),
        },
        "access_token": access_token,
    }


@app.get("/userinfo")
async def userinfo(access_token: str):
    """UserInfo 엔드포인트에서 추가 사용자 정보 가져오기"""
    oidc_config = await get_oidc_config(OIDC_CONFIG["issuer"])

    async with httpx.AsyncClient() as client:
        response = await client.get(
            oidc_config["userinfo_endpoint"],
            headers={"Authorization": f"Bearer {access_token}"},
        )

    return response.json()
# GitHub Actions OIDC를 사용한 AWS 인증 (비밀번호 없음!)
# .github/workflows/deploy.yml

name: Deploy to AWS with OIDC

on:
  push:
    branches: [main]

# OIDC 토큰 발급을 위한 권한
permissions:
  id-token: write   # OIDC 토큰 요청 허용
  contents: read    # 코드 체크아웃 허용

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      # GitHub OIDC로 AWS 인증 (장기 credential 불필요!)
      - name: Configure AWS credentials via OIDC
        uses: aws-actions/configure-aws-credentials@v4
        with:
          # AWS IAM Role ARN (OIDC 신뢰 관계 설정 필요)
          role-to-assume: arn:aws:iam::123456789012:role/GitHubActionsRole
          # 세션 이름 (CloudTrail 추적용)
          role-session-name: github-actions-${{ github.run_id }}
          # AWS 리전
          aws-region: ap-northeast-2

      # OIDC 토큰 확인 (디버깅용)
      - name: Check OIDC token claims
        run: |
          # GitHub가 발급한 OIDC 토큰 요청
          OIDC_TOKEN=$(curl -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
            "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=sts.amazonaws.com" \
            | jq -r '.value')

          # 토큰 페이로드 확인 (서명 검증 없이 디코딩만)
          echo "OIDC Token Claims:"
          echo $OIDC_TOKEN | cut -d. -f2 | base64 -d 2>/dev/null | jq .

          # 주요 클레임:
          # - iss: https://token.actions.githubusercontent.com
          # - sub: repo:owner/repo:ref:refs/heads/main
          # - aud: sts.amazonaws.com
          # - repository: owner/repo
          # - ref: refs/heads/main
          # - workflow: Deploy to AWS

      - name: Deploy to S3
        run: |
          aws s3 sync ./dist s3://my-bucket/
          echo "Deployed with OIDC authentication!"

---
# AWS IAM Role 신뢰 정책 (Trust Policy)
# 이 정책을 role에 적용해야 GitHub Actions가 인증 가능

# {
#   "Version": "2012-10-17",
#   "Statement": [
#     {
#       "Effect": "Allow",
#       "Principal": {
#         "Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"
#       },
#       "Action": "sts:AssumeRoleWithWebIdentity",
#       "Condition": {
#         "StringEquals": {
#           "token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
#         },
#         "StringLike": {
#           "token.actions.githubusercontent.com:sub": "repo:my-org/my-repo:*"
#         }
#       }
#     }
#   ]
# }

# OIDC Provider 생성 (AWS CLI)
# aws iam create-open-id-connect-provider \
#   --url https://token.actions.githubusercontent.com \
#   --client-id-list sts.amazonaws.com \
#   --thumbprint-list 6938fd4d98bab03faadb97b34396831e3780aea1

🗣️ Say It Like This in Practice

💬 In an Authentication Architecture Meeting
"Let's implement OIDC instead of using OAuth 2.0 alone. Sooner or later the question 'Who is this user?' will come up, and OAuth only does authorization, not authentication. With OIDC, you can receive the user's identity through the ID Token, and you can also fetch profile information through the UserInfo endpoint. Thanks to the Discovery Document, configuration is automated as well."
💬 In a code review
"Don't use Implicit Flow, because the token is exposed in the URL, which is risky. We need to switch to Authorization Code Flow + PKCE. PKCE is required even for public clients like SPAs and mobile apps. The way it works is that you SHA256-hash the code_verifier and send it as the code_challenge, then verify with the original verifier when exchanging the token."
💬 In a DevOps Pipeline Design
"Don't store AWS_SECRET_ACCESS_KEY in GitHub Actions. If you connect with OIDC, GitHub issues a JWT and AWS verifies it and gives you temporary credentials. If you set repository and branch conditions in the IAM Role trust policy, you can restrict deployment to the main branch only. It automates the principle of least privilege without any long-lived credentials."

⚠️ Cautions & Best Practices

❌
Skipping ID Token Validation

You must not just decode the ID Token you receive. You must always verify the signature (JWKS), issuer (iss), audience (aud), expiration time (exp), and nonce. Trusting a token tampered with by an attacker as-is can lead to account takeover.

❌
Using Implicit Flow

With Implicit Flow, the token is exposed in the URL fragment and can leak through browser history and the Referer header. It has been officially deprecated in the OAuth 2.0 Security BCP since 2021. Use Authorization Code Flow + PKCE.

❌
Insufficient redirect_uri Validation

Allowing a wildcard in redirect_uri makes you vulnerable to Open Redirect attacks. Register only exact URIs in a whitelist, and verify that the protocol (https), domain, and path all match exactly.

✅
OIDC Best Practices

Follow these practices: always use PKCE, keep the ID Token lifetime at 15 minutes or less, prevent CSRF/replay with state and nonce, cache JWKS keys and refresh them periodically, minimize scope (openid profile email), manage client_secret securely for confidential clients, and use the Access Token only on the server while minimizing its exposure to the client.

🔗 Related Terms

📚 Learn More