Authentication
Authentication
A security process that verifies the identity of a user or system. Verifies "who you are" in various ways, including passwords, MFA, biometrics, and OAuth. Distinct from Authorization.
Authentication
A security process that verifies the identity of a user or system. Verifies "who you are" in various ways, including passwords, MFA, biometrics, and OAuth. Distinct from Authorization.
Authentication is the process of verifying "who you are." As the first gateway of security, it verifies that the entity attempting to access a system (user, service, or device) matches the identity it claims. Authentication is classified into three factors: knowledge-based (password, PIN), possession-based (mobile phone, security key), and biometric-based (fingerprint, face). Combining two or more of these results in MFA (multi-factor authentication).
In modern authentication systems, token-based authentication is the standard. When a user logs in, the server issues a JWT (JSON Web Token) or a session token, and verifies identity with this token on every subsequent request. OAuth 2.0 and OpenID Connect (OIDC) are standard protocols for third-party authentication, enabling social login such as "Sign in with Google." SAML is used to implement SSO (Single Sign-On) in enterprise environments.
Password-based authentication is the most vulnerable method. It is exposed to phishing, credential stuffing, and brute-force attacks. The FIDO2/WebAuthn standard emerged to address this. It uses physical security keys (YubiKey) or platform authenticators (Windows Hello, Touch ID) to authenticate securely without a password. Passkey is a next-generation authentication method based on FIDO2, jointly supported by Apple, Google, and Microsoft.
In AI/ML systems, authentication is central to API access control. ML model APIs authenticate clients with API keys, OAuth tokens, and mTLS (mutual TLS). In MLOps pipelines, service-to-service authentication is handled with Workload Identity or SPIFFE/SPIRE. In federated learning, the identity of participating nodes is cryptographically verified to prevent malicious nodes from participating.
# JWT 기반 인증 - Python FastAPI
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from datetime import datetime, timedelta
from pydantic import BaseModel
import os
app = FastAPI()
# 설정
SECRET_KEY = os.environ.get("JWT_SECRET", "your-secret-key")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# 비밀번호 해싱
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# 모델
class User(BaseModel):
username: str
email: str | None = None
disabled: bool | None = None
class UserInDB(User):
hashed_password: str
class Token(BaseModel):
access_token: str
token_type: str
# 가상 데이터베이스
fake_users_db = {
"alice": {
"username": "alice",
"email": "alice@example.com",
"hashed_password": pwd_context.hash("secret123"),
"disabled": False,
}
}
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""비밀번호 검증"""
return pwd_context.verify(plain_password, hashed_password)
def get_user(db: dict, username: str) -> UserInDB | None:
"""사용자 조회"""
if username in db:
return UserInDB(**db[username])
return None
def authenticate_user(db: dict, username: str, password: str) -> UserInDB | bool:
"""사용자 인증"""
user = get_user(db, username)
if not user or not verify_password(password, user.hashed_password):
return False
return user
def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
"""JWT 액세스 토큰 생성"""
to_encode = data.copy()
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=15))
to_encode.update({"exp": expire})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
"""토큰에서 현재 사용자 추출"""
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
except JWTError:
raise credentials_exception
user = get_user(fake_users_db, username)
if user is None:
raise credentials_exception
return user
# 엔드포인트
@app.post("/token", response_model=Token)
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
"""로그인 및 토큰 발급"""
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token = create_access_token(
data={"sub": user.username},
expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
)
return {"access_token": access_token, "token_type": "bearer"}
@app.get("/users/me", response_model=User)
async def read_users_me(current_user: User = Depends(get_current_user)):
"""현재 사용자 정보 (인증 필요)"""
return current_user
@app.get("/ml/predict")
async def predict(current_user: User = Depends(get_current_user)):
"""ML 추론 API (인증 필요)"""
return {"user": current_user.username, "prediction": 0.95}
// JWT 인증 미들웨어 - Node.js Express + Passport
const express = require('express');
const passport = require('passport');
const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const app = express();
app.use(express.json());
// 설정
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
const JWT_EXPIRES_IN = '30m';
// 가상 데이터베이스
const users = new Map();
// Passport JWT 전략 설정
const jwtOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: JWT_SECRET,
};
passport.use(new JwtStrategy(jwtOptions, async (payload, done) => {
try {
const user = users.get(payload.sub);
if (user) {
return done(null, user);
}
return done(null, false);
} catch (error) {
return done(error, false);
}
}));
app.use(passport.initialize());
// 인증 미들웨어
const authenticate = passport.authenticate('jwt', { session: false });
// 회원가입
app.post('/register', async (req, res) => {
const { username, email, password } = req.body;
if (users.has(username)) {
return res.status(400).json({ error: 'User already exists' });
}
// 비밀번호 해싱 (bcrypt, cost factor 12)
const hashedPassword = await bcrypt.hash(password, 12);
const user = {
id: Date.now().toString(),
username,
email,
hashedPassword,
createdAt: new Date(),
};
users.set(username, user);
res.status(201).json({ message: 'User created', username });
});
// 로그인
app.post('/login', async (req, res) => {
const { username, password } = req.body;
const user = users.get(username);
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// 비밀번호 검증
const isValid = await bcrypt.compare(password, user.hashedPassword);
if (!isValid) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// JWT 토큰 생성
const token = jwt.sign(
{
sub: user.username,
email: user.email,
iat: Math.floor(Date.now() / 1000),
},
JWT_SECRET,
{ expiresIn: JWT_EXPIRES_IN }
);
res.json({
access_token: token,
token_type: 'Bearer',
expires_in: JWT_EXPIRES_IN,
});
});
// 보호된 라우트 - 사용자 정보
app.get('/me', authenticate, (req, res) => {
const { hashedPassword, ...userInfo } = req.user;
res.json(userInfo);
});
// 보호된 라우트 - ML 추론 API
app.post('/api/ml/predict', authenticate, (req, res) => {
const { input } = req.body;
// ML 추론 로직 (예시)
const prediction = {
user: req.user.username,
input,
result: Math.random(),
confidence: 0.95,
timestamp: new Date(),
};
res.json(prediction);
});
// 토큰 갱신
app.post('/refresh', authenticate, (req, res) => {
const newToken = jwt.sign(
{ sub: req.user.username, email: req.user.email },
JWT_SECRET,
{ expiresIn: JWT_EXPIRES_IN }
);
res.json({ access_token: newToken, token_type: 'Bearer' });
});
app.listen(3000, () => console.log('Server running on port 3000'));
# OAuth 2.0 Authorization Code Flow (PKCE)
# 1. 클라이언트: PKCE 코드 생성
# code_verifier: 43-128자 랜덤 문자열
CODE_VERIFIER=$(openssl rand -base64 32 | tr -d /=+ | cut -c -43)
# code_challenge: code_verifier의 SHA256 해시 (Base64URL 인코딩)
CODE_CHALLENGE=$(echo -n $CODE_VERIFIER | openssl sha256 -binary | base64 | tr +/ -_ | tr -d =)
echo "Code Verifier: $CODE_VERIFIER"
echo "Code Challenge: $CODE_CHALLENGE"
# 2. 사용자를 인증 서버로 리다이렉트 (Authorization Request)
# 브라우저에서 이 URL로 이동
AUTH_URL="https://auth.example.com/authorize?\
response_type=code&\
client_id=my-ml-app&\
redirect_uri=http://localhost:3000/callback&\
scope=openid%20profile%20email%20ml.predict&\
state=random-state-string&\
code_challenge=$CODE_CHALLENGE&\
code_challenge_method=S256"
echo "Authorization URL: $AUTH_URL"
# 3. 사용자 인증 후 콜백으로 authorization_code 수신
# http://localhost:3000/callback?code=AUTH_CODE&state=random-state-string
# 4. Authorization Code를 Access Token으로 교환
AUTH_CODE="received-auth-code"
curl -X POST https://auth.example.com/oauth/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=authorization_code" \
-d "code=$AUTH_CODE" \
-d "redirect_uri=http://localhost:3000/callback" \
-d "client_id=my-ml-app" \
-d "code_verifier=$CODE_VERIFIER"
# 응답 예시:
# {
# "access_token": "eyJhbGciOiJSUzI1NiIs...",
# "token_type": "Bearer",
# "expires_in": 3600,
# "refresh_token": "dGhpcyBpcyBhIHJlZnJlc2g...",
# "id_token": "eyJhbGciOiJSUzI1NiIs...",
# "scope": "openid profile email ml.predict"
# }
# 5. Access Token으로 API 호출
ACCESS_TOKEN="eyJhbGciOiJSUzI1NiIs..."
curl -X POST https://api.example.com/ml/predict \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"input": [1.0, 2.0, 3.0]}'
# 6. Refresh Token으로 새 Access Token 발급
REFRESH_TOKEN="dGhpcyBpcyBhIHJlZnJlc2g..."
curl -X POST https://auth.example.com/oauth/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=refresh_token" \
-d "refresh_token=$REFRESH_TOKEN" \
-d "client_id=my-ml-app"
# 7. 토큰 검증 (Introspection)
curl -X POST https://auth.example.com/oauth/introspect \
-H "Content-Type: application/x-www-form-urlencoded" \
-u "my-ml-app:client-secret" \
-d "token=$ACCESS_TOKEN"
"Authentication verifies 'who you are,' and authorization verifies 'what you can do.' You must not confuse the two. Our API authenticates with JWT and authorizes with RBAC."
"Passwords alone are vulnerable to phishing attacks. Applying MFA with a TOTP app or a FIDO2 security key can prevent over 99% of account takeovers. It's mandatory for administrator accounts, and let's roll it out gradually to regular users as well."
"Let's handle service-to-service authentication with mTLS and have external clients use the OAuth 2.0 PKCE flow. We validate tokens at the API Gateway, and pass the verified user context to internal services as headers."
If you store passwords in plaintext or with a simple hash (MD5, SHA1), they are exposed immediately when the database is leaked. Use slow hash functions such as bcrypt or Argon2id, and apply a salt.
If the JWT signing key is exposed, an attacker can generate arbitrary tokens. Load the key from environment variables or a secrets manager, and rotate it periodically. Using an asymmetric algorithm such as RS256 is recommended.
If an access token remains valid for a long time, the damage is greater when the token is stolen. Set access tokens to 15-30 minutes and refresh tokens to 7-30 days. Require re-authentication for sensitive operations.
Enable MFA by default, and consider adopting Passkey/FIDO2. Implement login attempt limits (Rate Limiting) and account lockout. Log all authentication events, and monitor for suspicious patterns.