OAuth 2.0 allows applications to access user resources without sharing the password. Google Login, GitHub Login — that is OAuth.
Flows¶
- Authorization Code + PKCE: Web and mobile (recommended)
- Client Credentials: Machine-to-machine
- Device Authorization: TV, IoT
- Implicit (DEPRECATED): Do not use
Authorization Code + PKCE¶
import hashlib, base64, secrets code_verifier = secrets.token_urlsafe(64) code_challenge = base64.urlsafe_b64encode( hashlib.sha256(code_verifier.encode()).digest() ).rstrip(b’=’).decode()
Exchange code for tokens¶
token = requests.post(“https://auth.example.com/token”, data={ “grant_type”: “authorization_code”, “code”: authorization_code, “client_id”: “myapp”, “code_verifier”: code_verifier, }).json()
Client Credentials¶
token = requests.post(“https://auth.example.com/token”, data={ “grant_type”: “client_credentials”, “client_id”: “service-a”, “client_secret”: “secret”, “scope”: “api.read”, }).json()
Key Takeaway¶
Auth Code + PKCE for web/mobile, Client Credentials for M2M. Always validate state, short token expiration.