🔒 Security

SSO

Single Sign-On

A unified authentication method that allows access to multiple services and applications with a single login. An Identity Provider (IdP) centrally manages user authentication, using protocols such as SAML 2.0, OAuth 2.0, and OIDC. Modern enterprises use an average of 371 SaaS applications, and SSO is a key technology that improves both security and user experience in such environments.

📖 Detailed Explanation

SSO (Single Sign-On) is an authentication architecture that lets users access multiple applications with a single set of credentials. The key is that an Identity Provider (IdP) performs user authentication centrally, and service providers (SPs) trust the IdP's authentication result. For example, when you log in with a Google account, you can access Gmail, YouTube, and Google Drive without logging in separately. This is the concept of "delegated authentication": instead of each service managing its own passwords, authentication is entrusted to a trusted IdP.

The main SSO protocols are chosen according to use case. SAML 2.0 is XML-based and suits enterprise environments with Active Directory integration, compliance, and audit requirements. OAuth 2.0 focuses on authorization and is used by third-party apps to obtain permission to access user data. OIDC (OpenID Connect) adds an authentication layer on top of OAuth 2.0 and is most commonly used to implement social login in mobile apps and web applications. As of 2025, 72% of enterprises have adopted multi-protocol SSO.

The security benefits of SSO are clear. 80% of web application attacks use stolen credentials; SSO reduces the number of passwords users have to remember, encouraging the use of strong passwords and shrinking the phishing attack surface. In addition, user provisioning and deprovisioning are managed centrally, so a departing employee's access to all systems can be cut off immediately. However, because the IdP can become a single point of failure (SPOF), applying MFA (multi-factor authentication) is essential.

Modern SSO implementations follow the "secure by design" principle. SAML assertions are signed with an HSM (Hardware Security Module), OIDC token lifetime is limited to 15 minutes, and user synchronization via SCIM is encrypted with AES-256. In a Zero Trust architecture, SSO is the entry point for continuous verification, evaluating context (device, location, behavior patterns) on every request to dynamically determine session validity. With AI-based attacks up 4,000% since 2022, SSO combined with adaptive authentication is essential.

💻 Code Example

// OIDC SSO 구현 예제 - Node.js (Passport.js)
const express = require('express');
const passport = require('passport');
const { Issuer, Strategy } = require('openid-client');

const app = express();

// OIDC 프로바이더 설정 (예: Okta, Auth0, Keycloak)
async function setupOIDC() {
    // 1. IdP의 Discovery Document에서 설정 자동 로드
    const issuer = await Issuer.discover(
        'https://your-idp.com/.well-known/openid-configuration'
    );
    console.log('Discovered issuer:', issuer.metadata.issuer);

    // 2. OIDC 클라이언트 등록
    const client = new issuer.Client({
        client_id: process.env.OIDC_CLIENT_ID,
        client_secret: process.env.OIDC_CLIENT_SECRET,
        redirect_uris: ['https://your-app.com/callback'],
        response_types: ['code'],  // Authorization Code Flow
    });

    // 3. Passport 전략 설정
    passport.use('oidc', new Strategy(
        {
            client,
            params: {
                // 최소한의 필요한 scope만 요청 (최소 권한 원칙)
                scope: 'openid profile email',
            },
            // PKCE 활성화 (public client 보안 강화)
            usePKCE: true,
        },
        (tokenSet, userinfo, done) => {
            // ID Token 검증은 라이브러리가 자동 수행
            // - 서명 검증 (JWKS 사용)
            // - 발급자(iss) 확인
            // - 대상(aud) 확인
            // - 만료 시간(exp) 확인

            console.log('ID Token claims:', tokenSet.claims());
            console.log('User info:', userinfo);

            // 사용자 정보로 세션 생성
            return done(null, {
                id: userinfo.sub,
                email: userinfo.email,
                name: userinfo.name,
                // Access Token은 API 호출에 사용
                accessToken: tokenSet.access_token,
                // Refresh Token으로 세션 연장
                refreshToken: tokenSet.refresh_token,
            });
        }
    ));

    return client;
}

// 세션 직렬화
passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((user, done) => done(null, user));

// 라우트 설정
app.get('/login', passport.authenticate('oidc'));

app.get('/callback',
    passport.authenticate('oidc', {
        failureRedirect: '/login-error',
        successRedirect: '/dashboard'
    })
);

// 로그아웃 (Single Logout)
app.get('/logout', async (req, res) => {
    const idToken = req.user?.idToken;
    req.logout(() => {
        // IdP에도 로그아웃 요청 (Single Logout)
        const logoutUrl = `https://your-idp.com/logout?` +
            `id_token_hint=${idToken}&` +
            `post_logout_redirect_uri=${encodeURIComponent('https://your-app.com')}`;
        res.redirect(logoutUrl);
    });
});

// 보호된 리소스
app.get('/dashboard', ensureAuthenticated, (req, res) => {
    res.json({ user: req.user, message: 'Welcome!' });
});

function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) return next();
    res.redirect('/login');
}

setupOIDC().then(() => {
    app.listen(3000, () => console.log('SSO app running on port 3000'));
});
# SAML SSO 구현 예제 - Python (Flask + python3-saml)
from flask import Flask, request, redirect, session, url_for
from onelogin.saml2.auth import OneLogin_Saml2_Auth
from onelogin.saml2.utils import OneLogin_Saml2_Utils
import json

app = Flask(__name__)
app.secret_key = 'your-secret-key'

def init_saml_auth(req):
    """SAML 인증 객체 초기화"""
    auth = OneLogin_Saml2_Auth(req, custom_base_path='saml/')
    return auth

def prepare_flask_request(request):
    """Flask 요청을 python3-saml 형식으로 변환"""
    return {
        'https': 'on' if request.scheme == 'https' else 'off',
        'http_host': request.host,
        'server_port': request.environ.get('SERVER_PORT', '443'),
        'script_name': request.path,
        'get_data': request.args.copy(),
        'post_data': request.form.copy(),
    }

@app.route('/saml/login')
def saml_login():
    """SAML 인증 시작 - IdP로 리다이렉트"""
    req = prepare_flask_request(request)
    auth = init_saml_auth(req)

    # RelayState로 원래 요청 URL 보존
    return_to = request.args.get('next', url_for('dashboard'))

    # AuthnRequest 생성 및 IdP로 리다이렉트
    sso_url = auth.login(return_to=return_to)
    return redirect(sso_url)

@app.route('/saml/acs', methods=['POST'])
def saml_acs():
    """Assertion Consumer Service - IdP 응답 처리"""
    req = prepare_flask_request(request)
    auth = init_saml_auth(req)

    # SAML Response 처리 및 검증
    auth.process_response()
    errors = auth.get_errors()

    if errors:
        return f'SAML Error: {", ".join(errors)}', 400

    if not auth.is_authenticated():
        return 'Not authenticated', 401

    # SAML Assertion에서 사용자 정보 추출
    session['saml_user'] = {
        'name_id': auth.get_nameid(),
        'name_id_format': auth.get_nameid_format(),
        'session_index': auth.get_session_index(),
        'attributes': auth.get_attributes(),
    }

    # 사용자 속성 매핑 (IdP 설정에 따라 다름)
    attrs = auth.get_attributes()
    session['user'] = {
        'email': attrs.get('email', [None])[0],
        'name': attrs.get('displayName', [None])[0],
        'department': attrs.get('department', [None])[0],
        'roles': attrs.get('memberOf', []),
    }

    # 원래 요청 URL로 리다이렉트
    relay_state = request.form.get('RelayState', url_for('dashboard'))
    return redirect(relay_state)

@app.route('/saml/slo', methods=['GET', 'POST'])
def saml_slo():
    """Single Logout - 모든 SP에서 로그아웃"""
    req = prepare_flask_request(request)
    auth = init_saml_auth(req)

    if request.method == 'GET':
        # SP 시작 SLO
        name_id = session.get('saml_user', {}).get('name_id')
        session_index = session.get('saml_user', {}).get('session_index')

        return redirect(auth.logout(
            name_id=name_id,
            session_index=session_index,
            return_to=url_for('index')
        ))
    else:
        # IdP 시작 SLO 응답 처리
        auth.process_slo()
        session.clear()
        return redirect(url_for('index'))

@app.route('/saml/metadata')
def saml_metadata():
    """SP 메타데이터 제공 (IdP 등록용)"""
    req = prepare_flask_request(request)
    auth = init_saml_auth(req)
    settings = auth.get_settings()
    metadata = settings.get_sp_metadata()
    errors = settings.validate_metadata(metadata)

    if errors:
        return f'Metadata Error: {", ".join(errors)}', 400

    return metadata, 200, {'Content-Type': 'text/xml'}

@app.route('/dashboard')
def dashboard():
    """보호된 리소스"""
    if 'user' not in session:
        return redirect(url_for('saml_login', next=request.url))

    return f"Welcome, {session['user']['name']}!"

# settings.json 예시 (saml/settings.json)
"""
{
    "sp": {
        "entityId": "https://your-app.com/saml/metadata",
        "assertionConsumerService": {
            "url": "https://your-app.com/saml/acs",
            "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
        },
        "singleLogoutService": {
            "url": "https://your-app.com/saml/slo",
            "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
        }
    },
    "idp": {
        "entityId": "https://your-idp.com",
        "singleSignOnService": {
            "url": "https://your-idp.com/sso",
            "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
        },
        "x509cert": "-----BEGIN CERTIFICATE-----...-----END CERTIFICATE-----"
    },
    "security": {
        "authnRequestsSigned": true,
        "wantAssertionsSigned": true,
        "wantMessagesSigned": true,
        "signatureAlgorithm": "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
    }
}
"""
// Spring Security OAuth2/OIDC SSO 구현 예제
// build.gradle에 의존성 추가
// implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'

// application.yml
/*
spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: ${OKTA_CLIENT_ID}
            client-secret: ${OKTA_CLIENT_SECRET}
            scope: openid, profile, email
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
          google:
            client-id: ${GOOGLE_CLIENT_ID}
            client-secret: ${GOOGLE_CLIENT_SECRET}
            scope: openid, profile, email
        provider:
          okta:
            issuer-uri: https://your-domain.okta.com
*/

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.web.SecurityFilterChain;

import java.util.*;
import java.util.stream.Collectors;

@Configuration
@EnableWebSecurity
public class SsoSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                // 공개 경로
                .requestMatchers("/", "/login", "/error").permitAll()
                // 관리자 전용
                .requestMatchers("/admin/**").hasRole("ADMIN")
                // 나머지는 인증 필요
                .anyRequest().authenticated()
            )
            .oauth2Login(oauth2 -> oauth2
                // 커스텀 로그인 페이지
                .loginPage("/login")
                // 로그인 성공 후 리다이렉트
                .defaultSuccessUrl("/dashboard", true)
                // 커스텀 UserService로 권한 매핑
                .userInfoEndpoint(userInfo -> userInfo
                    .oidcUserService(oidcUserService())
                )
            )
            .logout(logout -> logout
                .logoutSuccessUrl("/")
                // OIDC RP-Initiated Logout
                .logoutSuccessHandler(oidcLogoutSuccessHandler())
            );

        return http.build();
    }

    @Bean
    public OAuth2UserService oidcUserService() {
        final OidcUserService delegate = new OidcUserService();

        return userRequest -> {
            // 기본 OIDC 사용자 정보 로드
            OidcUser oidcUser = delegate.loadUser(userRequest);

            // IdP의 그룹/역할 클레임을 Spring Security 권한으로 매핑
            Set mappedAuthorities = new HashSet<>();

            // 기본 권한
            mappedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));

            // IdP 그룹을 역할로 변환 (예: Okta groups 클레임)
            List groups = oidcUser.getAttribute("groups");
            if (groups != null) {
                groups.stream()
                    .map(group -> new SimpleGrantedAuthority("ROLE_" + group.toUpperCase()))
                    .forEach(mappedAuthorities::add);
            }

            // 커스텀 클레임 처리 (예: 부서별 권한)
            String department = oidcUser.getAttribute("department");
            if ("IT".equals(department)) {
                mappedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            }

            return new DefaultOidcUser(
                mappedAuthorities,
                oidcUser.getIdToken(),
                oidcUser.getUserInfo()
            );
        };
    }

    @Bean
    public OidcClientInitiatedLogoutSuccessHandler oidcLogoutSuccessHandler() {
        OidcClientInitiatedLogoutSuccessHandler handler =
            new OidcClientInitiatedLogoutSuccessHandler(clientRegistrationRepository);
        handler.setPostLogoutRedirectUri("{baseUrl}");
        return handler;
    }
}

// 컨트롤러에서 사용자 정보 접근
@RestController
public class UserController {

    @GetMapping("/api/me")
    public Map getCurrentUser(
            @AuthenticationPrincipal OidcUser oidcUser) {
        return Map.of(
            "sub", oidcUser.getSubject(),
            "email", oidcUser.getEmail(),
            "name", oidcUser.getFullName(),
            "authorities", oidcUser.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList())
        );
    }
}

🗣️ Say It Like This in Practice

💬 In an IAM architecture meeting
"We'll go with SAML for enterprise apps and OIDC for consumer apps. SAML integrates well with AD and meets audit log requirements, while OIDC is mobile-friendly and makes social login easy to implement. 72% of enterprises run multi-protocol like this. Choose either Okta or Azure AD as the IdP, and MFA must be applied."
💬 In a security review
"SSO can make the IdP a single point of failure (SPOF), so a high-availability setup is a must. We also need to limit token lifetime to 15 minutes and enable PKCE. Stolen credentials account for 80% of attacks, so we have to shrink the phishing attack surface with the SSO + MFA combination. Immediately deactivating a departing employee's account also only works properly with centralized SSO."
💬 In development team onboarding
"When adding a new service, just register the SP with the IdP and configure the SAML metadata or the OIDC redirect_uri. Don't implement login yourself. Request only scopes like openid profile email, with least privilege, and the library handles ID token validation. It fetches the public key from the JWKS endpoint and verifies the signature."

⚠️ Cautions & Best Practices

❌
SSO without MFA

SSO alone is not secure enough. If the IdP is compromised, every service is at risk. Always apply MFA on top of SSO. With AI-based attacks up 4,000%, phishing-resistant MFA such as passkeys or hardware tokens is recommended.

❌
Choosing the wrong protocol

SAML suits enterprise/legacy, and OIDC suits modern web/mobile. Using SAML for a mobile app causes XML parsing overhead and UX problems. For a new project, choose OIDC by default. Even if you only need OAuth, it's good to implement OIDC in case you need authentication later.

❌
Not implementing Single Logout

If you unify only login and handle logout separately in each service, session mismatches occur. Implement SAML SLO or OIDC RP-Initiated Logout so that users are logged out of all services at once.

✅
SSO best practices

Use a 15-minute OIDC token lifetime + Refresh Token, sign SAML assertions with an HSM, enforce PKCE, minimize scopes (openid profile email), automate provisioning/deprovisioning with SCIM, set up the IdP for high availability, and implement automatic permission assignment by role/department/location through policy-based access control.

🔗 Related Terms

📚 Learn More