OAuth2 集成:通过 Spring Security 实现单点登录与第三方登录!

🏆本文收录于「滚雪球学SpringBoot」专栏,手把手带你零基础入门Spring Boot,从入门到就业,助你早日登顶实现财富自由🚀;同时,欢迎大家关注&&收藏&&订阅!持续更新中,up!up!up!!
@TOC
环境说明:Windows 10 + IntelliJ IDEA 2021.3.2 + Jdk 1.8
📝 前言:OAuth2,让登录变得更加简单与安全!
在今天的互联网应用中,用户登录已经成为了不可或缺的一部分。尤其是当应用程序的规模越来越大,用户账户越来越多时,如何简化登录流程,同时保证安全性,成为了开发者们必须解决的一个难题。
而OAuth2就是为了解决这个问题而诞生的,它通过授权机制,使得用户可以在不透露用户名和密码的情况下,安全地授权第三方应用访问自己的资源。结合Spring Security,OAuth2为我们提供了一个非常强大的单点登录(SSO)方案,让用户在多个应用之间进行无缝登录。
本文将详细介绍如何使用Spring Security OAuth2实现单点登录,并集成第三方登录(如Google、GitHub)。如果你正在为应用的登录问题烦恼,那就继续往下看,轻松搞定OAuth2集成!
🔒 OAuth2 集成:简化安全认证的利器 🛡️
1️⃣ OAuth2 简介:授权与认证的完美结合
OAuth2是一个授权框架,允许第三方应用在不暴露用户的用户名和密码的前提下,安全地访问用户的资源。它通过授权码(Authorization Code)、客户端凭证(Client Credentials)、密码(Password)等不同的授权方式,支持多种安全认证机制。
OAuth2通常用于以下场景:
- 单点登录(SSO):用户只需要登录一次,就可以访问多个不同的应用。
- 第三方授权登录:用户可以使用第三方账户(如Google、GitHub)进行登录,而无需创建新账户。
2️⃣ Spring Security OAuth2:集成 OAuth2 的利器
Spring Security OAuth2是Spring Security的扩展模块,用于帮助开发者轻松实现OAuth2的认证与授权。它提供了OAuth2客户端、OAuth2资源服务器、OAuth2授权服务器等一系列功能,能够让开发者更加方便地实现OAuth2协议。
Spring Security OAuth2能够为你的应用提供:
- 单点登录(SSO):多个应用共享同一个认证服务器,用户只需登录一次。
- 第三方登录:通过集成Google、GitHub等第三方服务,用户可以用已有的账户快速登录。
🧑💻 使用 Spring Security OAuth2 实现单点登录(SSO) 🔑
1️⃣ 创建 Spring Boot 项目
在开始之前,确保你已经创建了一个Spring Boot项目,并在pom.xml
中添加了必要的依赖。
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Spring Security OAuth2 Client -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
</dependency>
<!-- Spring Security OAuth2 Resource Server -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-resource-server</artifactId>
</dependency>
<!-- Spring Boot Starter Thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Spring Boot Starter Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- H2 Database for testing -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
这里我们使用Spring Security、Spring OAuth2客户端、Spring Security的资源服务器功能以及Thymeleaf来搭建前端界面,数据库用H2进行测试。
2️⃣ 配置 OAuth2 单点登录(SSO)
我们通过配置application.yml
或者application.properties
来设置OAuth2的客户端信息,包括授权服务器的URL、客户端ID、客户端密钥等信息。以下是一个application.yml
的配置示例:
spring:
security:
oauth2:
client:
registration:
# 注册一个OAuth2客户端
google:
client-id: your-google-client-id
client-secret: your-google-client-secret
scope: profile, email
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
authorization-grant-type: authorization_code
client-name: Google
provider: google
provider:
google:
authorization-uri: https://accounts.google.com/o/oauth2/v2/auth
token-uri: https://oauth2.googleapis.com/token
user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
user-name-attribute: sub
在这个配置中,我们配置了Google的OAuth2登录。client-id
和client-secret
可以在Google开发者控制台中获取。redirect-uri
是用户登录成功后重定向回应用的地址。
3️⃣ OAuth2 登录成功后的处理
用户登录成功后,Spring Security会自动将用户的基本信息存储在OAuth2AuthenticationToken
中。你可以在你的应用中使用这些信息,比如用户的用户名、电子邮件等。
你可以创建一个控制器来显示用户的基本信息:
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class UserController {
@GetMapping("/user")
public String user(@AuthenticationPrincipal OAuth2User principal, Model model) {
model.addAttribute("name", principal.getAttribute("name"));
model.addAttribute("email", principal.getAttribute("email"));
return "user"; // 返回显示用户信息的视图
}
}
这里,@AuthenticationPrincipal
注解会从Spring Security的上下文中获取当前已认证的用户,OAuth2User
对象包含了从OAuth2提供商(如Google)获取的用户信息。
4️⃣ 配置 SecurityConfig
为了保护你的应用的安全性,我们需要配置SecurityConfig
来设置OAuth2登录的路径和权限控制:
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login", "/oauth2/authorization/google").permitAll() // 允许公开访问登录页
.anyRequest().authenticated() // 其他请求需要认证
.and()
.oauth2Login() // 启用OAuth2登录
.defaultSuccessUrl("/user", true); // 登录成功后跳转到用户信息页面
}
}
通过oauth2Login()
,Spring Security会自动启用OAuth2的登录功能,并在登录成功后跳转到/user
页面,显示用户信息。
🌐 集成第三方登录:Google & GitHub 登录示例 💻
1️⃣ 集成 Google 登录
如前所述,我们已经在application.yml
中配置了Google的OAuth2信息。接下来,我们需要去Google开发者控制台申请OAuth2认证信息,并将客户端ID和密钥填入配置文件中。
- 访问Google Cloud Console,创建项目。
- 在“API和服务”中创建OAuth2凭据,获取客户端ID和客户端密钥。
- 将这些信息填入
application.yml
中。
用户现在可以通过点击“使用Google登录”按钮,进行Google的OAuth2认证,认证成功后,用户将被重定向到/user
页面,展示他们的基本信息。
2️⃣ 集成 GitHub 登录
同样地,GitHub也支持OAuth2认证。你只需要在application.yml
中添加GitHub的配置信息:
spring:
security:
oauth2:
client:
registration:
github:
client-id: your-github-client-id
client-secret: your-github-client-secret
scope: read:user
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
authorization-grant-type: authorization_code
client-name: GitHub
provider: github
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: login
填写完GitHub的client-id
和client-secret
后,用户就能通过GitHub账户登录。
3️⃣ 创建前端登录按钮
你可以在前端页面中创建登录按钮,用户点击后将跳转到相应的OAuth2提供商页面进行登录:
<a href="/oauth2/authorization/google">Login with Google</a>
<a href="/oauth2/authorization/github">Login with GitHub</a>
通过以上配置,用户可以选择使用Google或GitHub账户登录。
🎯 总结:OAuth2 实现现代应用的登录机制
通过Spring Security OAuth2,我们轻松实现了单点登录(SSO)和集成第三方登录(如Google、GitHub)。OAuth2不仅提升了用户体验,让用户能够用已有的社交账户快速登录,还保证了安全性,因为用户无需在每个应用中输入自己的用户名和密码。
无论是构建一个支持单点登录的大型系统,还是需要集成第三方登录的小型应用,Spring Security OAuth2都能提供强大的支持,让你的登录机制变得更加简洁、安全、高效。
希望你在本文中学到了如何使用Spring Security OAuth2实现单点登录和第三方登录!如果你有任何问题或建议,欢迎随时留言讨论!🎉
🧧福利赠与你🧧
无论你是计算机专业的学生,还是对编程有兴趣的小伙伴,都建议直接毫无顾忌的学习此专栏「滚雪球学SpringBoot」,bug菌郑重承诺,凡是学习此专栏的同学,均能获取到所需的知识和技能,全网最快速入门SpringBoot,就像滚雪球一样,越滚越大, 无边无际,指数级提升。
最后,如果这篇文章对你有所帮助,帮忙给作者来个一键三连,关注、点赞、收藏,您的支持就是我坚持写作最大的动力。
同时欢迎大家关注公众号:「猿圈奇妙屋」 ,以便学习更多同类型的技术文章,免费白嫖最新BAT互联网公司面试题、4000G pdf电子书籍、简历模板、技术文章Markdown文档等海量资料。
✨️ Who am I?
我是bug菌,CSDN | 掘金 | InfoQ | 51CTO | 华为云 | 阿里云 | 腾讯云 等社区博客专家,C站博客之星Top30,华为云多年度十佳博主/价值贡献奖,掘金多年度人气作者Top40,掘金等各大社区平台签约作者,51CTO年度博主Top12,掘金/InfoQ/51CTO等社区优质创作者;全网粉丝合计 30w+;更多精彩福利点击这里;硬核微信公众号「猿圈奇妙屋」,欢迎你的加入!免费白嫖最新BAT互联网公司面试真题、4000G PDF电子书籍、简历模板等海量资料,你想要的我都有,关键是你不来拿。

-End-
- 点赞
- 收藏
- 关注作者
评论(0)