1.登录gitee,创建一个第三方登录的应用
首先找到设置中的第三方应用:
2.引入pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
3.application.yml
spring:
security:
oauth2:
client:
registration:
gitee:
#应用id
client-id: 创建的应用中获取xxxxxxxxxxxxx
#应用密钥
client-secret: 创建应用中获取xxxxxxxxx
#应用名称
client-name: MyLinging
#授权后重定向url
redirect-uri: http://127.0.0.1:8080/login/oauth2/code/gitee
#授权码模式
authorization-grant-type: authorization_code
provider:
gitee:
# Gitee 的授权 URL
authorization-uri: https://gitee.com/oauth/authorize
# token获取url
token-uri: https://gitee.com/oauth/token
# 用户信息获取url
user-info-uri: https://gitee.com/api/v5/user
# 码云用户信息中的用户名字段 这里就取id作为唯一标志
user-name-attribute: id
4.配置文件
httpSecurity.oauth2Login(cus -> cus
//登录认证入口(前端发起请求的路径)
//例如:http://127.0.0.1:8080/oauth2/authorization/gitee
.authorizationEndpoint(authorization -> authorization.baseUri("/oauth2/authorization"))
//用户确认后,第三方服务器回调的路径
.redirectionEndpoint(redirection -> redirection.baseUri("/login/oauth2/code/*"))
// 处理第三方返回的用户信息
.userInfoEndpoint(userInfo -> userInfo.userService(new DefaultOAuth2UserService()))
// 三方认证成功后重定向的地址,此处本机测试,搭建前后端分离项目,授权后重定向前端首页地址,仅后端测试可注释掉不配置
.defaultSuccessUrl("http://127.0.0.1:8081")
)
5.测试
-
点击gitee登录,访问登录授权的入口:
http://127.0.0.1:8080/oauth2/authorization/gitee
-
访问后会重定向到gitee授权页面:
https://gitee.com/oauth/authorize?response_type=code&client_id=xxxxxx&state=oihEUItlxWQEEsnz2in1VSo9w3Za7WUcwcShzQ1_IRg%3D&redirect_uri=http://127.0.0.1:8080/login/oauth2/code/gitee
-
当用户点击同意授权时,会向gitee授权服务器请求授权获取code:
https://gitee.com/oauth/authorize
-
请求授权完后,回调到:
http://127.0.0.1:8080/login/oauth2/code/gitee?code=xxxxxxxxxxx&state=oihEUItlxWQEEsnz2in1VSo9w3Za7WUcwcShzQ1_IRg%3D
然后由springsecurity的OAuth2LoginAuthenticationFilter
进行拦截,由OAuth2LoginAuthenticationProvider
、OAuth2AuthorizationCodeAuthenticationProvider
根据code向gitee进行认证拿到token,然后根据token由DefaultOAuth2UserService
的loadUser向gitee获取用户的信息,并封装DefaultOAuth2User对象保存在SecurityContextHolder中,然后认证完就重定向到首页。这里设置了重定向地址是http://127.0.0.1:8081/,如下: