OAuth 2.0 + OIDC 认证架构设计:从理论到实战
OAuth 2.0 and OIDC Authentication Architecture From Theory to Practice
| iDev Team | 2026-08-05T05:22:00
OAuth 2.0 和 OpenID Connect 是现代认证的基石。本文用简洁的语言解释核心概念,并给出 Spring Boot 集成 Google/GitHub 登录的完整代码。
OAuth 2.0 and OpenID Connect are the foundation of modern authentication. This article explains core concepts clearly and provides complete Spring Boot code for Google/GitHub login integration.
OAuth 2.0 解决什么问题 假设你的应用需要访问用户的 Google 日历数据。你不应该让用户把 Google 密码告诉你——这既不安全,用户也不愿意。OAuth 2.0 的方案是:用户在 Google 的页面上授权,Google 给你一个有限权限的 Token,你用这个 Token 访问数据。 核心角色 Resource Owner:用户(数据的所有者) Client:你的应用(想访问数据的一方) Authorization Server:Google/GitHub 的认证服务器 Resource Server:存储用户数据的服务器 OIDC 是什么 OpenID Connect (OIDC) 是建立在 OAuth 2.0 之上的身份认证协议。OAuth 2.0 解决的是"授权"(你能做什么),OIDC 解决的是"认证"(你是谁)。OIDC 在 OAuth 2.0 的基础上增加了 ID Token,包含用户的基本信息(姓名、邮箱、头像)。 Authorization Code 流程 用户点击"用 Google 登录" 应用重定向到 Google 授权页面 用户在 Google 页面登录并授权 Google 重定向回你的应用,带上一个 authorization code 你的后端用 code 向 Google 换取 access_token 和 id_token 从 id_token 中解析出用户信息,完成登录 Spring Boot 集成示例 # application.yml spring: security: oauth2: client: registration: google: client-id: your-google-client-id client-secret: your-google-secret scope: openid,email,profile github: client-id: your-github-client-id client-secret: your-github-secret scope: user:email Spring Boot 3 + Spring Security 6 只需要配置 client-id 和 secret,框架自动处理整个 OAuth 2.0 / OIDC 流程。 安全注意事项 始终使用 Authorization Code 流程(不要用 Implicit 流程,已被废弃) 使用 PKCE 扩展防止授权码拦截攻击 验证 ID Token 的签名和 audience Token 存储使用 HttpOnly + Secure Cookie
What OAuth 2.0 Solves Suppose your app needs to access a user's Google Calendar data. You shouldn't ask for their Google password — that's insecure and users won't comply. OAuth 2.0's solution: the user authorizes on Google's page, Google gives you a limited-permission Token, and you use that Token to access data. OIDC Explained OpenID Connect (OIDC) is an identity authentication protocol built on top of OAuth 2.0. OAuth 2.0 handles "authorization" (what you can do), OIDC handles "authentication" (who you are). OIDC adds an ID Token containing basic user information (name, email, avatar). Spring Boot Integration Spring Boot 3 + Spring Security 6 only requires configuring client-id and secret — the framework automatically handles the entire OAuth 2.0 / OIDC flow. Security Considerations Always use Authorization Code flow (Implicit flow is deprecated) Use PKCE extension to prevent authorization code interception Validate ID Token signature and audience Store tokens in HttpOnly + Secure Cookies