活动地址:CSDN21天学习挑战赛
Spring Security 5中集成了OAuth的客户端模块,该模块包含以下三个子模块:
源代码地址:https://github.com/jujunchen/21Study
新创建一个Spring Boot 工程,pom依赖如下
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--单元测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
注意: 必须引入spring-boot-starter-oauth2-client
依赖
在GitHub上注册一个OAuth应用
地址是:https://github.com/settings/applications/new
注册界面如下:
点击 Register application按钮注册,注册完成得到clientId和clientSecret
接下来在配置文件中增加对于的配置
spring:
security:
oauth2:
client:
registration:
github:
client-id: github-client-id
client-secret: github-client-secret
其中: (1)spring.security.oauth2.client.registration是OAuth客户端所有属性的基础前缀。
(2)registration下面的github是ClientRegistration的唯一ID。
Spring Security OAuth 默认的重定向模板是{baseUrl}/login/oauth2/code/{registrationId}
,registrationId
是ClientRegistration的唯一ID,通常以接入的OAuth服务提供商的简称来命名即可,所以此处设置为 github。
github-client-id和github-client-secret需要替换为前面在GitHub上注册得到的clientId和clientSecret。
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(Principal principal) {
return "Hello," + principal.getName();
}
}
principal对象由Spring框架自动注入,表示当前登录的用户。
3. 点击Authorize xxx(授权)按钮后,回调到http://localhost:8080/login/oauth2/code/github?code=dc3a0c2d3a77a8ade7dc&state=Pq69SdJxwxeV-nY4aLkX-DGu31qWNFl-5EMRml1sRdM%3D
地址,该地址就为前面配置的OAuth认证的重定向地址,code 和 state为 github 自动拼接。最终浏览器显示"Hello,xxx"
由于github在国内经常超时,后面将介绍如何使用Gitee进行集成登录。