2026/3/27 14:49:15
网站建设
项目流程
网站空间在哪买,商务门户网站怎么做,wordpress 可视化插件,wordpress cdn 发帖子视频看了几百小时还迷糊#xff1f;关注我#xff0c;几分钟让你秒懂#xff01;#xff08;发点评论可以给博主加热度哦#xff09; #x1f31f; 一、需求场景#xff1a;为什么我们要用 OAuth2.0#xff1f;
想象一下这些场景#xff1a;
用户不想注册账号#…视频看了几百小时还迷糊关注我几分钟让你秒懂发点评论可以给博主加热度哦 一、需求场景为什么我们要用 OAuth2.0想象一下这些场景用户不想注册账号只想用微信/支付宝/Google 快速登录你的网站你的 App 需要调用 GitHub API 获取用户仓库信息公司内部多个系统如 HR 系统、OA 系统希望统一登录避免重复输入账号密码。这些问题的通用解决方案就是OAuth2.0—— 一种安全、标准的授权框架。⚠️ 注意OAuth2.0 是「授权」协议不是「认证」协议。但它常被用于实现“第三方登录”如微信登录此时结合了 OpenID ConnectOIDC等扩展。在 Spring Boot 中我们可以通过spring-boot-starter-oauth2-client轻松集成主流平台如 GitHub、Google、微信等的 OAuth2 登录功能。 二、正例Spring Boot OAuth2.0 实现 GitHub 第三方登录✅ 步骤 1创建 Spring Boot 项目依赖如下pom.xmldependencies dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-oauth2-client/artifactId /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-thymeleaf/artifactId /dependency /dependencies✅ 步骤 2配置 application.ymlspring: security: oauth2: client: registration: github: client-id: YOUR_GITHUB_CLIENT_ID client-secret: YOUR_GITHUB_CLIENT_SECRET scope: read:user provider: github: authorization-uri: https://github.com/login/oauth/authorize token-uri: https://github.com/login/oauth/access_token user-info-uri: https://api.github.com/user user-name-attribute: id 如何获取client-id和client-secret登录 GitHub Developer Settings创建新 OAuth App回调地址填http://localhost:8080/login/oauth2/code/github✅ 步骤 3配置 Security 安全策略Configuration EnableWebSecurity public class SecurityConfig { Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authz - authz .requestMatchers(/, /login**).permitAll() .anyRequest().authenticated() ) .oauth2Login(oauth2 - oauth2 .loginPage(/login) // 自定义登录页可选 .defaultSuccessUrl(/profile, true) // 登录成功跳转 ); return http.build(); } }✅ 步骤 4创建控制器和页面Controller public class HomeController { GetMapping(/) public String home() { return index; } GetMapping(/profile) public String profile(Model model, OAuth2AuthenticationToken authentication) { if (authentication ! null) { MapString, Object attributes authentication.getPrincipal().getAttributes(); model.addAttribute(name, attributes.get(name)); model.addAttribute(avatar, attributes.get(avatar_url)); } return profile; } }templates/index.html!DOCTYPE html html headtitle首页/title/head body h1欢迎来到我的网站/h1 a href/oauth2/authorization/github使用 GitHub 登录/a /body /htmltemplates/profile.html!DOCTYPE html html xmlns:thhttp://www.thymeleaf.org headtitle个人资料/title/head body h1你好span th:text${name}User/span/h1 img th:src${avatar} width100 / a href/logout退出登录/a /body /html✅ 启动项目访问http://localhost:8080→ 点击“使用 GitHub 登录” → 跳转到 GitHub 授权页 → 授权后返回你的/profile页面显示用户名和头像❌ 三、反例常见错误写法千万别这么干反例 1把 client-secret 写死在代码里// ❌ 千万不要这样 Bean public ClientRegistrationRepository clientRegistrationRepository() { ClientRegistration github ClientRegistration.withRegistrationId(github) .clientId(your_real_id) .clientSecret(your_real_secret) // ← 泄露风险极高 .build(); return new InMemoryClientRegistrationRepository(github); } 正确做法使用application.yml 环境变量或配置中心如 Nacos、Apollo生产环境绝不能明文写密钥反例 2忽略 HTTPS生产环境大忌OAuth2.0 的回调地址在 GitHub 等平台强制要求 HTTPS本地 localhost 除外。如果你部署到公网却用 HTTP会报错The redirect_uri MUST match the registered callback URL✅ 解决方案部署时务必配 HTTPS或使用 Ngrok / Cloudflare Tunnel 临时测试。反例 3未处理用户拒绝授权用户点击“Cancel”后GitHub 会重定向到你的回调地址并带上erroraccess_denied。如果你没处理可能报 500 错误。✅ 建议自定义失败处理器.oauth2Login(oauth2 - oauth2 .failureHandler((request, response, exception) - { response.sendRedirect(/login?erroroauth_failed); }) )⚠️ 四、注意事项小白必看问题说明OAuth2 ≠ JWTOAuth2 是授权框架JWT 是令牌格式二者常搭配但不等同scope 权限最小化只申请必要权限如 GitHub 用read:user而非userstate 参数防 CSRFSpring Security 默认已启用无需手动处理用户信息字段不同GitHub 返回id、name、avatar_urlGoogle 返回sub、email、picture注意user-name-attribute配置多平台支持可同时配置 GitHub、Google、微信需自定义 Provider 五、扩展如何接入微信登录微信 OAuth2 不完全兼容标准如 userinfo 返回 JSON 格式特殊需自定义CustomOAuth2UserService。但 GitHub/Google 等标准平台Spring Boot 开箱即用✅ 总结OAuth2.0 让用户安全地授权第三方访问资源Spring Boot 通过oauth2-client极简集成配置client-id/secret Security 策略即可实现第三方登录切记密钥保密、HTTPS、错误处理、权限最小化。视频看了几百小时还迷糊关注我几分钟让你秒懂发点评论可以给博主加热度哦