Batch 5: Protocols & Security Networking Apache & NGINX Docker ← Full TOC

← Protocols Index

🛡️ Identity & Access Management — OAuth2, JWT, SAML, SSO, Kerberos, MFA, RBAC, IPA

Modern identity systems handle authentication (who are you?) and authorization (what can you do?). OAuth2 and OIDC are the web standards. SAML is the enterprise standard. Kerberos is the network standard. FreeIPA combines LDAP, Kerberos, and DNS for Linux environments.

📋 Reference

ItemSyntax / ValueDescription
AuthenticationVerify identity — who are you?Password, certificate, biometric, token
AuthorizationWhat actions are permitted?Roles, permissions, policies
SSOSingle Sign-On — one login, many appsLog in once to Okta/AD, access all services
OAuth2Authorization framework — delegate access'Login with Google' — app gets token, not password
OAuth2 flowsAuthorization Code, Client Credentials, DeviceAuthorization Code = web apps, Client Credentials = M2M
OIDCOpenID Connect — identity layer on top of OAuth2OAuth2 + ID token (JWT with user info)
JWTJSON Web Token — signed token with claimsHeader.Payload.Signature — stateless auth
JWT structureeyJhbGci.eyJzdWIi.signatureBase64url(header).Base64url(payload).signature
JWT claimssub, iss, aud, exp, iat, nbf, jtisub=subject, exp=expiry, iss=issuer
JWT verifyCheck signature + exp + iss + audNever trust JWT without signature verification!
Bearer tokenAuthorization: Bearer <jwt>JWT sent in Authorization header
Refresh tokenLong-lived token to get new access tokensAccess token expires fast (15min), refresh = hours/days
SAMLSecurity Assertion Markup Language — XML-based SSOEnterprise SSO: Okta, ADFS, Shibboleth
SAML SPService Provider — the applicationRedirects to IdP for authentication
SAML IdPIdentity Provider — authenticates usersAD FS, Okta, OneLogin, Azure AD
SAML assertionXML document proving identityContains attributes: email, name, groups
MFAMulti-Factor AuthenticationSomething you know + have + are
TOTPTime-based One-Time Password — RFC 6238Google Authenticator, Authy — 6-digit code changes every 30s
FIDO2/WebAuthnHardware security key authenticationYubiKey, Windows Hello, Touch ID — phishing resistant
RBACRole-Based Access ControlRoles: admin, editor, viewer — assign to users
ABACAttribute-Based Access ControlPolicies based on user attributes, resource, environment
KerberosNetwork authentication protocol — ticketsActive Directory uses Kerberos internally
KDCKey Distribution CenterKerberos server: Authentication Server + Ticket Granting Server
TGTTicket Granting Ticket — proves identity to KDCkinit alice@EXAMPLE.COM — get TGT
Service ticketTicket for specific service — from TGSklist shows current tickets
FreeIPARed Hat's identity management — LDAP+Kerberos+DNSIntegrated IdM for Linux/UNIX environments
Okta / Azure ADCloud identity providersEnterprise SSO, MFA, lifecycle management
PAMPluggable Authentication ModulesLinux authentication framework — pam_krb5, pam_ldap

💡 Example

# ── JWT — Generate and Verify (Python) ───────────────────────
# pip install pyjwt cryptography

import jwt
import datetime
import secrets

SECRET_KEY = secrets.token_hex(32)  # In production: load from secrets manager!

# Generate JWT (access token)
def create_token(user_id: str, email: str, roles: list, expires_minutes: int = 15):
    now = datetime.datetime.utcnow()
    payload = {
        'sub':   user_id,                              # subject
        'email': email,
        'roles': roles,
        'iss':   'https://auth.mywebuniversity.com',   # issuer
        'aud':   'https://api.mywebuniversity.com',    # audience
        'iat':   now,                                  # issued at
        'exp':   now + datetime.timedelta(minutes=expires_minutes),  # expiry
        'jti':   secrets.token_hex(16),                # JWT ID (unique)
    }
    return jwt.encode(payload, SECRET_KEY, algorithm='HS256')

# Verify JWT
def verify_token(token: str) -> dict:
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'],
                             audience='https://api.mywebuniversity.com')
        return payload
    except jwt.ExpiredSignatureError:
        raise ValueError("Token has expired")
    except jwt.InvalidTokenError as e:
        raise ValueError(f"Invalid token: {e}")

# Usage
token = create_token("usr_1001", "alice@mywebuniversity.com", ["student", "editor"])
print(f"Token: {token[:40]}...")

payload = verify_token(token)
print(f"User:  {payload['email']}")
print(f"Roles: {payload['roles']}")
print(f"Expires: {datetime.datetime.fromtimestamp(payload['exp'])}")

# ── OAuth2 Authorization Code Flow ───────────────────────────
# Step 1: Redirect user to provider
import urllib.parse
params = {
    'client_id':     'mywebuniversity-client-id',
    'redirect_uri':  'https://www.mywebuniversity.com/auth/callback',
    'response_type': 'code',
    'scope':         'openid email profile',
    'state':         secrets.token_urlsafe(16),  # CSRF protection
    'nonce':         secrets.token_urlsafe(16),  # Replay protection
}
auth_url = 'https://accounts.google.com/o/oauth2/v2/auth?' + urllib.parse.urlencode(params)
print(f"Redirect to: {auth_url[:80]}...")

# Step 2: Exchange code for tokens (server-side)
import requests
def exchange_code(code: str, state: str, expected_state: str) -> dict:
    if state != expected_state:
        raise ValueError("State mismatch — possible CSRF attack!")
    resp = requests.post('https://oauth2.googleapis.com/token', data={
        'code':          code,
        'client_id':     'mywebuniversity-client-id',
        'client_secret': 'client-secret-from-google-console',
        'redirect_uri':  'https://www.mywebuniversity.com/auth/callback',
        'grant_type':    'authorization_code',
    })
    return resp.json()  # access_token, id_token, refresh_token

# ── Kerberos ──────────────────────────────────────────────────
# Get Kerberos ticket (authenticate)
kinit alice@MYWEBUNIVERSITY.COM
# Enter password — get TGT valid for 24 hours

# List current tickets
klist
# Krb5 Credentials Cache: KEYRING:persistent:1000
# Default principal: alice@MYWEBUNIVERSITY.COM
# Valid starting     Expires            Service principal
# 06/27/2026 08:00  06/28/2026 08:00  krbtgt/MYWEBUNIVERSITY.COM

# Use with curl (GSSAPI/Negotiate authentication)
curl --negotiate -u : https://kerberized-app.mywebuniversity.com/

# Destroy ticket
kdestroy

# ── FreeIPA ───────────────────────────────────────────────────
# Install IPA client on Linux
sudo apt install freeipa-client
sudo ipa-client-install --domain=mywebuniversity.com \
  --server=ipa.mywebuniversity.com \
  --principal=admin --password=adminpass

# IPA commands (on IPA server)
ipa user-add alice --first=Alice --last=Smith --email=alice@mywebuniversity.com
ipa user-mod alice --title="Senior Developer"
ipa group-add developers --desc="Development team"
ipa group-add-member developers --users=alice,bob
ipa user-find --login=alice
ipa hbacrule-add allow_ssh_to_webservers --usercat=all --hostcat=all
ipa hbacrule-add-service allow_ssh_to_webservers --hbacsvcs=ssh

← REST APIs & curl  |  🏠 Index  |  Cybersecurity Fundamentals →