Skip to content
  • Sponsor twelvet-projects/twelvet

  • Notifications You must be signed in to change notification settings
  • Fork 57

Commit decfe8d

Browse files
committedJan 17, 2025·
✨ Spring Security Oauth2
1 parent bad2378 commit decfe8d

File tree

6 files changed

+119
-150
lines changed

6 files changed

+119
-150
lines changed
 

‎twelvet-auth/pom.xml

+6-6
Original file line numberDiff line numberDiff line change
@@ -51,12 +51,6 @@
5151
<artifactId>twelvet-framework-security</artifactId>
5252
</dependency>
5353

54-
<!--OAuth2 Client-->
55-
<dependency>
56-
<groupId>org.springframework.security</groupId>
57-
<artifactId>spring-security-oauth2-client</artifactId>
58-
</dependency>
59-
6054
<!--OAuth2-->
6155
<dependency>
6256
<groupId>org.springframework.boot</groupId>
@@ -99,6 +93,12 @@
9993
<artifactId>mica-xss</artifactId>
10094
</dependency>
10195

96+
<!--OAuth2第三方接入-->
97+
<dependency>
98+
<groupId>me.zhyd.oauth</groupId>
99+
<artifactId>JustAuth</artifactId>
100+
</dependency>
101+
102102
</dependencies>
103103

104104
<build>

‎twelvet-auth/src/main/java/com/twelvet/auth/config/CustomOAuth2UserService.java

+52-49
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,58 @@
1-
package com.twelvet.auth.config;
2-
3-
import com.twelvet.framework.utils.TUtils;
4-
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
5-
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
6-
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
7-
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
8-
import org.springframework.security.oauth2.core.user.OAuth2User;
9-
import org.springframework.util.Assert;
10-
11-
import java.util.Collections;
12-
import java.util.Map;
13-
import java.util.Objects;
14-
1+
/*
2+
* package com.twelvet.auth.config;
3+
*
4+
* import com.twelvet.framework.utils.TUtils; import
5+
* org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; import
6+
* org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; import
7+
* org.springframework.security.oauth2.client.userinfo.OAuth2UserService; import
8+
* org.springframework.security.oauth2.core.OAuth2AuthenticationException; import
9+
* org.springframework.security.oauth2.core.user.OAuth2User; import
10+
* org.springframework.util.Assert;
11+
*
12+
* import java.util.Collections; import java.util.Map; import java.util.Objects;
13+
*
14+
*/
1515
/**
1616
* @author twelvet
1717
* @WebSite twelvet.cn
1818
* @Description: 自定义获取第三方code换信息
19-
*/
20-
public class CustomOAuth2UserService<R extends OAuth2UserRequest, U extends OAuth2User>
21-
implements OAuth2UserService<R, U> {
22-
23-
/**
24-
* 默认的获取方式,适配大部分第三方
19+
*//*
20+
*
21+
* public class CustomOAuth2UserService<R extends OAuth2UserRequest, U extends
22+
* OAuth2User> implements OAuth2UserService<R, U> {
23+
*
2524
*/
26-
private final OAuth2UserService<OAuth2UserRequest, OAuth2User> defaultOAuth2UserService = new DefaultOAuth2UserService();
27-
28-
/**
29-
* 自定义换取方式
25+
/**
26+
* 默认的获取方式,适配大部分第三方
27+
*//*
28+
*
29+
* private final OAuth2UserService<OAuth2UserRequest, OAuth2User>
30+
* defaultOAuth2UserService = new DefaultOAuth2UserService();
31+
*
32+
*/
33+
/**
34+
* 自定义换取方式
35+
*//*
36+
*
37+
* private final Map<String, OAuth2UserService<R, U>> userServiceMap;
38+
*
39+
* public CustomOAuth2UserService(Map<String, OAuth2UserService<R, U>> userServiceMap)
40+
* { this.userServiceMap = Collections.unmodifiableMap(userServiceMap); }
41+
*
42+
* @SuppressWarnings("unchecked")
43+
*
44+
* @Override public U loadUser(R userRequest) throws OAuth2AuthenticationException {
45+
* Assert.notNull(userRequest, "userRequest cannot be null");
46+
*
47+
* // 第三方ID(可以通过此ID获取自定义授权方式) String registrationId =
48+
* userRequest.getClientRegistration().getRegistrationId();
49+
*
50+
* OAuth2UserService<R, U> oAuth2UserService = userServiceMap.get(registrationId);
51+
*
52+
* if (Objects.isNull(oAuth2UserService)) { // 采用默认换取方式 oAuth2UserService =
53+
* (OAuth2UserService<R, U>) defaultOAuth2UserService; }
54+
*
55+
* return oAuth2UserService.loadUser(userRequest); }
56+
*
57+
* }
3058
*/
31-
private final Map<String, OAuth2UserService<R, U>> userServiceMap;
32-
33-
public CustomOAuth2UserService(Map<String, OAuth2UserService<R, U>> userServiceMap) {
34-
this.userServiceMap = Collections.unmodifiableMap(userServiceMap);
35-
}
36-
37-
@SuppressWarnings("unchecked")
38-
@Override
39-
public U loadUser(R userRequest) throws OAuth2AuthenticationException {
40-
Assert.notNull(userRequest, "userRequest cannot be null");
41-
42-
// 第三方ID(可以通过此ID获取自定义授权方式)
43-
String registrationId = userRequest.getClientRegistration().getRegistrationId();
44-
45-
OAuth2UserService<R, U> oAuth2UserService = userServiceMap.get(registrationId);
46-
47-
if (Objects.isNull(oAuth2UserService)) {
48-
// 采用默认换取方式
49-
oAuth2UserService = (OAuth2UserService<R, U>) defaultOAuth2UserService;
50-
}
51-
52-
return oAuth2UserService.loadUser(userRequest);
53-
}
54-
55-
}

‎twelvet-auth/src/main/java/com/twelvet/auth/endpoint/TWTTokenEndpoint.java ‎twelvet-auth/src/main/java/com/twelvet/auth/controller/TWTTokenEndpoint.java

+7-9
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.twelvet.auth.endpoint;
1+
package com.twelvet.auth.controller;
22

33
import cn.hutool.core.util.StrUtil;
44
import com.twelvet.api.system.domain.SysClientDetails;
@@ -24,8 +24,6 @@
2424
import org.springframework.security.authentication.event.LogoutSuccessEvent;
2525
import org.springframework.security.core.Authentication;
2626
import org.springframework.security.core.context.SecurityContextHolder;
27-
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
28-
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
2927
import org.springframework.security.oauth2.core.OAuth2AccessToken;
3028
import org.springframework.security.oauth2.core.OAuth2Error;
3129
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
@@ -63,9 +61,6 @@ public class TWTTokenEndpoint {
6361
@Autowired
6462
private OAuth2AuthorizationService authorizationService;
6563

66-
@Autowired
67-
private ClientRegistrationRepository clientRegistrationRepository;
68-
6964
@Autowired
7065
private RemoteOauth2ClientDetailsService remoteOauth2ClientDetailsService;
7166

@@ -86,9 +81,12 @@ public class TWTTokenEndpoint {
8681
public ModelAndView require(ModelAndView modelAndView, @RequestParam(required = false) String error) {
8782
modelAndView.setViewName("/login");
8883
List<String> registrationIdList = new ArrayList<>();
89-
((InMemoryClientRegistrationRepository) clientRegistrationRepository).forEach(item -> {
90-
registrationIdList.add(item.getRegistrationId());
91-
});
84+
// 获取有多少第三方登录配置
85+
/*
86+
* ((InMemoryClientRegistrationRepository)
87+
* clientRegistrationRepository).forEach(item -> {
88+
* registrationIdList.add(item.getRegistrationId()); });
89+
*/
9290
modelAndView.addObject("registrationIdList", registrationIdList);
9391
modelAndView.addObject("error", error);
9492
return modelAndView;

‎twelvet-auth/src/main/java/com/twelvet/auth/endpoint/IndexController.java

-25
This file was deleted.

‎twelvet-auth/src/main/java/com/twelvet/auth/support/core/FormIdentityLoginConfigurer.java

+14-21
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,9 @@
11
package com.twelvet.auth.support.core;
22

3-
import com.twelvet.auth.config.CustomOAuth2UserService;
43
import com.twelvet.auth.support.handler.FormAuthenticationFailureHandler;
54
import com.twelvet.auth.support.handler.SsoLogoutSuccessHandler;
6-
import org.springframework.security.config.Customizer;
75
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
86
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
9-
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
10-
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
11-
import org.springframework.security.oauth2.core.user.OAuth2User;
12-
13-
import java.util.HashMap;
14-
import java.util.Map;
157

168
/**
179
* @author twelvet
@@ -36,19 +28,20 @@ public void init(HttpSecurity http) throws Exception {
3628
}).csrf(AbstractHttpConfigurer::disable);
3729

3830
// 开启第三方登录(GitHub)注意顺序,否则则会强制执行第三方登录优先
39-
Map<String, OAuth2UserService<OAuth2UserRequest, OAuth2User>> userServiceMap = new HashMap<>();
40-
http.oauth2Login(httpSecurityOAuth2LoginConfigurer -> httpSecurityOAuth2LoginConfigurer
41-
// .successHandler(new TWTAuthenticationSuccessEventHandler())
42-
.userInfoEndpoint(userInfo -> userInfo
43-
// 自定义授权,默认支持大部分OAuth2流程
44-
.userService(new CustomOAuth2UserService<>(userServiceMap)))
45-
// 需要提供能够呈现自定义登录页面的@Controller。@RequestMapping("/login/oauth2")
46-
// .loginPage("/login/oauth2")
47-
.authorizationEndpoint(authorization -> authorization
48-
// 默认发起请求地址:/oauth2/authorization/*
49-
.baseUri("/oauth2/authorization"))
50-
// 默认重定向:/login/oauth2/code/*
51-
.redirectionEndpoint(redirection -> redirection.baseUri("/login/oauth2/code/*")));
31+
/*
32+
* Map<String, OAuth2UserService<OAuth2UserRequest, OAuth2User>> userServiceMap =
33+
* new HashMap<>(); http.oauth2Login(httpSecurityOAuth2LoginConfigurer ->
34+
* httpSecurityOAuth2LoginConfigurer // .successHandler(new
35+
* TWTAuthenticationSuccessEventHandler()) .userInfoEndpoint(userInfo -> userInfo
36+
* // 自定义授权,默认支持大部分OAuth2流程 .userService(new
37+
* CustomOAuth2UserService<>(userServiceMap))) //
38+
* 需要提供能够呈现自定义登录页面的@Controller。@RequestMapping("/login/oauth2") //
39+
* .loginPage("/login/oauth2") .authorizationEndpoint(authorization ->
40+
* authorization // 默认发起请求地址:/oauth2/authorization/*
41+
* .baseUri("/oauth2/authorization")) // 默认重定向:/login/oauth2/code/*
42+
* .redirectionEndpoint(redirection ->
43+
* redirection.baseUri("/login/oauth2/code/*")));
44+
*/
5245
// Accept access tokens for User Info and/or Client Registration
5346
// .oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults()));
5447
}

‎twelvet-auth/src/main/resources/application.yml

+40-40
Original file line numberDiff line numberDiff line change
@@ -41,43 +41,43 @@ spring:
4141

4242

4343
# 接入第三方OAuth2登录(开发功能-dev)
44-
security:
45-
oauth2:
46-
client:
47-
# 注册第三方客户端
48-
registration:
49-
gitee:
50-
# 关联OAuth2 Server
51-
provider: gitee
52-
client-id: 3050796d8930eec5b
53-
client-secret: 77ca2fee35950
54-
# 授权类型
55-
authorization-grant-type: authorization_code
56-
# 授权范围
57-
scope: user_info
58-
# 回调地址
59-
redirect-uri: '{baseUrl}/{action}/oauth2/code/{registrationId}'
60-
client-name: gitee
61-
github:
62-
# 关联OAuth2 Server
63-
provider: github
64-
client-id: ffc6b9
65-
client-secret: 7d00bc26
66-
# 授权类型
67-
authorization-grant-type: authorization_code
68-
# 授权范围
69-
scope: user_info
70-
# 回调地址
71-
redirect-uri: '{baseUrl}/{action}/oauth2/code/{registrationId}'
72-
client-name: github
73-
# 第三方信息换取配置(默认Google、GitHub、Facebook 和 Okta内置)
74-
provider:
75-
gitee:
76-
# 登录地址
77-
authorization-uri: https://gitee.com/oauth/authorize
78-
# 换取token
79-
token-uri: https://gitee.com/oauth/token
80-
# 取得的user详情中的属性id的值作为Client的已认证的用户的用户名
81-
user-name-attribute: id
82-
# 获取用户信息
83-
user-info-uri: https://gitee.com/api/v5/user
44+
# security:
45+
# oauth2:
46+
# client:
47+
# # 注册第三方客户端
48+
# registration:
49+
# gitee:
50+
# # 关联OAuth2 Server
51+
# provider: gitee
52+
# client-id: 305079
53+
# client-secret: 77ca2
54+
# # 授权类型
55+
# authorization-grant-type: authorization_code
56+
# # 授权范围
57+
# scope: user_info
58+
# # 回调地址
59+
# redirect-uri: '{baseUrl}/{action}/oauth2/code/{registrationId}'
60+
# client-name: gitee
61+
# github:
62+
# # 关联OAuth2 Server
63+
# provider: github
64+
# client-id: ffc6b9
65+
# client-secret: 7d00bc26
66+
# # 授权类型
67+
# authorization-grant-type: authorization_code
68+
# # 授权范围
69+
# scope: user_info
70+
# # 回调地址
71+
# redirect-uri: '{baseUrl}/{action}/oauth2/code/{registrationId}'
72+
# client-name: github
73+
# # 第三方信息换取配置(默认Google、GitHub、Facebook 和 Okta内置)
74+
# provider:
75+
# gitee:
76+
# # 登录地址
77+
# authorization-uri: https://gitee.com/oauth/authorize
78+
# # 换取token
79+
# token-uri: https://gitee.com/oauth/token
80+
# # 取得的user详情中的属性id的值作为Client的已认证的用户的用户名
81+
# user-name-attribute: id
82+
# # 获取用户信息
83+
# user-info-uri: https://gitee.com/api/v5/user

0 commit comments

Comments
 (0)
Please sign in to comment.