hit : hits) {
+ Product product = hit.source();
+ log.info("找到产品 " + product.getSku() + ",得分 " + hit.score());
+ }
+
+
+ }
+}
diff --git a/elasticsearch-spring-boot-starter/src/test/java/com/admin4j/elasticsearch/ElasticsearchApplication.java b/elasticsearch-spring-boot-starter/src/test/java/com/admin4j/elasticsearch/ElasticsearchApplication.java
new file mode 100644
index 0000000..cdaed6c
--- /dev/null
+++ b/elasticsearch-spring-boot-starter/src/test/java/com/admin4j/elasticsearch/ElasticsearchApplication.java
@@ -0,0 +1,15 @@
+package com.admin4j.elasticsearch;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+/**
+ * @author andanyang
+ * @since 2023/12/15 10:08
+ */
+@SpringBootApplication
+public class ElasticsearchApplication {
+ public static void main(String[] args) {
+ SpringApplication.run(ElasticsearchApplication.class, args);
+ }
+}
diff --git a/elasticsearch-spring-boot-starter/src/test/java/com/admin4j/elasticsearch/entity/Product.java b/elasticsearch-spring-boot-starter/src/test/java/com/admin4j/elasticsearch/entity/Product.java
new file mode 100644
index 0000000..a219945
--- /dev/null
+++ b/elasticsearch-spring-boot-starter/src/test/java/com/admin4j/elasticsearch/entity/Product.java
@@ -0,0 +1,19 @@
+package com.admin4j.elasticsearch.entity;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/**
+ * @author andanyang
+ * @since 2023/12/15 10:28
+ */
+@Data
+@AllArgsConstructor
+@NoArgsConstructor
+public class Product {
+ private String sku;
+ private String name;
+ private double price;
+ private String description;
+}
diff --git a/elasticsearch-spring-boot-starter/src/test/resources/application.yml b/elasticsearch-spring-boot-starter/src/test/resources/application.yml
new file mode 100644
index 0000000..dbf2be0
--- /dev/null
+++ b/elasticsearch-spring-boot-starter/src/test/resources/application.yml
@@ -0,0 +1,9 @@
+spring:
+ elasticsearch:
+ uris:
+ - http://192.168.0.252:9200
+
+
+logging:
+ level:
+ org.springframework.data.elasticsearch.client.WIRE: TRACE
\ No newline at end of file
From 815926b525f38bd6e5b5c0b753b7cf334de1b7d9 Mon Sep 17 00:00:00 2001
From: andanyang <1218853253@qq.com>
Date: Mon, 18 Dec 2023 17:04:33 +0800
Subject: [PATCH 18/30] =?UTF-8?q?feat(security):=20security=20Authenticati?=
=?UTF-8?q?onManager=20=E4=BB=A3=E7=A0=81=E9=87=8D=E6=96=B0=E6=A2=B3?=
=?UTF-8?q?=E7=90=86?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
security-spring-boot-starter/pom.xml | 2 +-
.../MultiAuthenticationAutoConfiguration.java | 60 ++++++++++++++
...uthenticationManagerAutoConfiguration.java | 73 +++++++++++++++++
.../configuration/SecurityConfiguration.java | 80 ++++++-------------
.../UserTokenServiceConfiguration.java | 26 ------
.../MultiAuthenticationFilter.java | 21 ++---
.../MultiAuthenticationProvider.java | 11 ++-
.../MultiAuthenticationToken.java | 2 +-
.../MultiCheckUsernamePasswordService.java | 2 +-
.../MultiSecurityConfigurerAdapter.java | 16 ++--
.../MultiUserDetailsService.java | 2 +-
.../UsernamePasswordUserDetailsService.java | 8 +-
.../security/properties/CorsProperties.java | 2 +-
.../properties/FormLoginProperties.java | 8 ++
.../properties/IgnoringUrlProperties.java | 4 +-
.../main/resources/META-INF/spring.factories | 4 +-
16 files changed, 208 insertions(+), 113 deletions(-)
create mode 100644 security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/MultiAuthenticationAutoConfiguration.java
create mode 100644 security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/MultiAuthenticationManagerAutoConfiguration.java
rename security-spring-boot-starter/src/main/java/com/admin4j/framework/security/{mult => multi}/MultiAuthenticationFilter.java (86%)
rename security-spring-boot-starter/src/main/java/com/admin4j/framework/security/{mult => multi}/MultiAuthenticationProvider.java (95%)
rename security-spring-boot-starter/src/main/java/com/admin4j/framework/security/{mult => multi}/MultiAuthenticationToken.java (98%)
rename security-spring-boot-starter/src/main/java/com/admin4j/framework/security/{mult => multi}/MultiCheckUsernamePasswordService.java (98%)
rename security-spring-boot-starter/src/main/java/com/admin4j/framework/security/{mult => multi}/MultiSecurityConfigurerAdapter.java (66%)
rename security-spring-boot-starter/src/main/java/com/admin4j/framework/security/{mult => multi}/MultiUserDetailsService.java (96%)
rename security-spring-boot-starter/src/main/java/com/admin4j/framework/security/{mult => multi}/UsernamePasswordUserDetailsService.java (91%)
diff --git a/security-spring-boot-starter/pom.xml b/security-spring-boot-starter/pom.xml
index 22fb2d7..a491f78 100644
--- a/security-spring-boot-starter/pom.xml
+++ b/security-spring-boot-starter/pom.xml
@@ -10,7 +10,7 @@
com.admin4j.framework
security-spring-boot-starter
jar
- 0.9.3-SNAPSHOT
+ 0.9.4-SNAPSHOT
security-spring-boot-starter
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/MultiAuthenticationAutoConfiguration.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/MultiAuthenticationAutoConfiguration.java
new file mode 100644
index 0000000..9c21fab
--- /dev/null
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/MultiAuthenticationAutoConfiguration.java
@@ -0,0 +1,60 @@
+package com.admin4j.framework.security.configuration;
+
+import com.admin4j.framework.security.filter.JwtAuthenticationTokenFilter;
+import com.admin4j.framework.security.multi.MultiAuthenticationFilter;
+import com.admin4j.framework.security.multi.MultiSecurityConfigurerAdapter;
+import com.admin4j.framework.security.properties.FormLoginProperties;
+import com.admin4j.framework.security.properties.MultiAuthenticationProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Bean;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.web.authentication.AuthenticationFailureHandler;
+import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
+
+/**
+ * 多渠道配置自动登录
+ *
+ * @author andanyang
+ * @since 2023/12/15 16:15
+ */
+@ConditionalOnProperty(prefix = "admin4j.security.multi", value = "enable", matchIfMissing = true)
+public class MultiAuthenticationAutoConfiguration {
+
+ @Autowired
+ MultiAuthenticationProperties multiAuthenticationProperties;
+ @Autowired
+ AuthenticationSuccessHandler authenticationSuccessHandler;
+ @Autowired
+ AuthenticationFailureHandler authenticationFailureHandler;
+ @Autowired
+ FormLoginProperties formLoginProperties;
+
+
+ @Bean
+ @ConditionalOnMissingBean(MultiAuthenticationFilter.class)
+ public MultiAuthenticationFilter multiAuthenticationFilter(AuthenticationManager authenticationManager) {
+
+ MultiAuthenticationFilter authenticationFilter = new MultiAuthenticationFilter(multiAuthenticationProperties, formLoginProperties);
+ authenticationFilter.setAuthenticationManager(authenticationManager);
+ authenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
+ authenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
+ return authenticationFilter;
+ }
+
+ /**
+ * 多渠道认证功能配置
+ *
+ * @return
+ */
+ @Bean
+ @ConditionalOnMissingBean(MultiSecurityConfigurerAdapter.class)
+ public MultiSecurityConfigurerAdapter multiSecurityConfigurerAdapter(MultiAuthenticationFilter multiAuthenticationFilter,
+ JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter,
+ AuthenticationManager authenticationManager) throws Exception {
+
+
+ return new MultiSecurityConfigurerAdapter(multiAuthenticationFilter, authenticationManager, jwtAuthenticationTokenFilter);
+ }
+}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/MultiAuthenticationManagerAutoConfiguration.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/MultiAuthenticationManagerAutoConfiguration.java
new file mode 100644
index 0000000..641ce57
--- /dev/null
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/MultiAuthenticationManagerAutoConfiguration.java
@@ -0,0 +1,73 @@
+package com.admin4j.framework.security.configuration;
+
+import com.admin4j.framework.security.multi.MultiAuthenticationProvider;
+import com.admin4j.framework.security.multi.MultiUserDetailsService;
+import com.admin4j.framework.security.multi.UsernamePasswordUserDetailsService;
+import com.admin4j.framework.security.properties.FormLoginProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Bean;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.authentication.ProviderManager;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.crypto.password.PasswordEncoder;
+
+import java.util.List;
+
+/**
+ * 多渠道配置自动登录
+ *
+ * @author andanyang
+ * @since 2023/12/15 16:15
+ */
+@ConditionalOnProperty(prefix = "admin4j.security.multi", value = "enable", matchIfMissing = true)
+public class MultiAuthenticationManagerAutoConfiguration {
+
+ /**
+ * 默认的多渠道表单登录
+ *
+ * @return
+ */
+ @Bean
+ @ConditionalOnMissingBean(UsernamePasswordUserDetailsService.class)
+ @ConditionalOnBean(UserDetailsService.class)
+ // @ConditionalOnProperty(prefix = "admin4j.security.multi", name = "enable", matchIfMissing = true)
+ @ConditionalOnProperty(prefix = "admin4j.security.form-login", name = "enable", matchIfMissing = true)
+ public MultiUserDetailsService usernamePasswordUserDetailsService(
+ UserDetailsService userDetailsService,
+ PasswordEncoder passwordEncoder,
+ FormLoginProperties formLoginProperties
+ ) {
+
+ return new UsernamePasswordUserDetailsService(
+ passwordEncoder,
+ formLoginProperties,
+ userDetailsService
+ );
+ }
+
+
+ /**
+ * 获取 AuthenticationManager
+ *
+ * 或者:
+ *
+ * AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
+ * authenticationManagerBuilder.userDetailsService(userDetailsService);
+ * authenticationManager = authenticationManagerBuilder.build();
+ *
+ *
+ * @return
+ */
+
+ @Bean
+ @ConditionalOnMissingBean(AuthenticationManager.class)
+ public AuthenticationManager authenticationManager(@Autowired(required = false)
+ List userDetailServices) {
+
+ return new ProviderManager(new MultiAuthenticationProvider(userDetailServices));
+ }
+
+}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityConfiguration.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityConfiguration.java
index 61a82ad..20d9542 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityConfiguration.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityConfiguration.java
@@ -2,12 +2,8 @@
import com.admin4j.framework.security.ISecurityIgnoringUrl;
import com.admin4j.framework.security.filter.ActuatorFilter;
-import com.admin4j.framework.security.filter.JwtAuthenticationTokenFilter;
import com.admin4j.framework.security.ignoringUrl.AnonymousAccessUrl;
-import com.admin4j.framework.security.mult.MultiAuthenticationFilter;
-import com.admin4j.framework.security.mult.MultiAuthenticationProvider;
-import com.admin4j.framework.security.mult.MultiSecurityConfigurerAdapter;
-import com.admin4j.framework.security.mult.MultiUserDetailsService;
+import com.admin4j.framework.security.multi.MultiSecurityConfigurerAdapter;
import com.admin4j.framework.security.properties.FormLoginProperties;
import com.admin4j.framework.security.properties.IgnoringUrlProperties;
import com.admin4j.framework.security.properties.JwtProperties;
@@ -19,7 +15,6 @@
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
-import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
@@ -47,6 +42,8 @@
/**
* 开启方法级别的注解支持
+ *
+ * @author andanyang
*/
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableConfigurationProperties({IgnoringUrlProperties.class, JwtProperties.class, FormLoginProperties.class, MultiAuthenticationProperties.class})
@@ -72,21 +69,16 @@ public class SecurityConfiguration {
AnonymousAccessUrl anonymousAccessUrl;
@Autowired
LogoutSuccessHandler logoutSuccessHandler;
- @Autowired
- JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
- @Autowired(required = false)
- List usernamePasswordAuthenticationFilters;
- @Autowired
- MultiAuthenticationProperties multiAuthenticationProperties;
- @Autowired(required = false)
- List userDetailServices;
- @Autowired
- AuthenticationConfiguration authenticationConfiguration;
+ // @Autowired
+ // JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
+ // @Autowired(required = false)
+ // List usernamePasswordAuthenticationFilters;
@Autowired(required = false)
ActuatorFilter actuatorFilter;
@Autowired(required = false)
CorsFilter corsFilter;
-
+ @Autowired(required = false)
+ MultiSecurityConfigurerAdapter multiSecurityConfigurerAdapter;
/**
* 取消ROLE_前缀
@@ -137,35 +129,27 @@ public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Excepti
;
// 添加Logout filter
- httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
- // 添加JWT filter
- httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
+ httpSecurity.logout().logoutUrl(formLoginProperties.getLogOutProcessingUrl()).permitAll().logoutSuccessHandler(logoutSuccessHandler);
+
+ // 授权请求配置
+ // 忽略URl配置
+ ignoringRequestMatcherRegistry(httpSecurity.authorizeRequests());
+ // 除上面外的所有请求全部需要鉴权认证;其他路径必须验证
+ httpSecurity.authorizeRequests().anyRequest().authenticated();
+
// 添加CORS filter
if (corsFilter != null) {
- httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
+ httpSecurity.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class);
}
-
- if (usernamePasswordAuthenticationFilters != null && usernamePasswordAuthenticationFilters.size() > 0) {
- usernamePasswordAuthenticationFilters.forEach(usernameFilter -> httpSecurity.addFilterBefore(usernameFilter, UsernamePasswordAuthenticationFilter.class));
+ if (actuatorFilter != null) {
+ httpSecurity.addFilterBefore(actuatorFilter, UsernamePasswordAuthenticationFilter.class);
}
-
-
- authorizeRequestsConfigurer(httpSecurity);
-
+
// 多渠道登录
- if (multiAuthenticationProperties.isEnable()) {
-
- MultiAuthenticationFilter authenticationFilter = new MultiAuthenticationFilter(multiAuthenticationProperties, formLoginProperties);
-
- authenticationFilter.setAuthenticationManager(authenticationConfiguration.getAuthenticationManager());
- authenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
- authenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
-
- MultiSecurityConfigurerAdapter multiSecurityConfigurerAdapter = new MultiSecurityConfigurerAdapter(authenticationFilter, new MultiAuthenticationProvider(userDetailServices));
+ if (multiSecurityConfigurerAdapter != null) {
httpSecurity.apply(multiSecurityConfigurerAdapter);
-
- } else {
+ } else if (formLoginProperties.isEnable()) {
// 开启form表单认证
httpSecurity.formLogin()
.loginProcessingUrl(formLoginProperties.getLoginProcessingUrl())
@@ -174,29 +158,11 @@ public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Excepti
.failureHandler(authenticationFailureHandler)
.successHandler(authenticationSuccessHandler)
.permitAll();
-
- }
-
- if (actuatorFilter != null) {
- httpSecurity.addFilterBefore(actuatorFilter, UsernamePasswordAuthenticationFilter.class);
}
- // GlobalAuthenticationConfigurerAdapter
- // WebSecurityConfigurerAdapter
return httpSecurity.build();
}
- /**
- * 授权请求配置
- */
- private void authorizeRequestsConfigurer(HttpSecurity httpSecurity) throws Exception {
- ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry expressionInterceptUrlRegistry =
- httpSecurity.authorizeRequests();
- // 忽略URl配置
- ignoringRequestMatcherRegistry(expressionInterceptUrlRegistry);
- // 除上面外的所有请求全部需要鉴权认证;其他路径必须验证
- expressionInterceptUrlRegistry.anyRequest().authenticated();
- }
/**
* 忽略URl配置
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/UserTokenServiceConfiguration.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/UserTokenServiceConfiguration.java
index 58345e7..95cafac 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/UserTokenServiceConfiguration.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/UserTokenServiceConfiguration.java
@@ -7,20 +7,15 @@
import com.admin4j.framework.security.filter.ActuatorFilter;
import com.admin4j.framework.security.jwt.JwtUserDetailsService;
import com.admin4j.framework.security.jwt.JwtUserTokenService;
-import com.admin4j.framework.security.mult.MultiCheckUsernamePasswordService;
-import com.admin4j.framework.security.mult.UsernamePasswordUserDetailsService;
import com.admin4j.framework.security.properties.ActuatorProperties;
-import com.admin4j.framework.security.properties.FormLoginProperties;
import com.admin4j.framework.security.properties.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
-import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@@ -46,27 +41,6 @@ public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
- /**
- * 默认的表达登录
- *
- * @return
- */
- @Bean
- @ConditionalOnMissingBean(MultiCheckUsernamePasswordService.class)
- @ConditionalOnBean(UserDetailsService.class)
- @ConditionalOnProperty(prefix = "admin4j.security.multi", name = "enable", matchIfMissing = true)
- public UsernamePasswordUserDetailsService usernamePasswordUserDetailsService(
- UserDetailsService userDetailsService,
- PasswordEncoder passwordEncoder,
- FormLoginProperties formLoginProperties) {
-
- return new UsernamePasswordUserDetailsService(
- passwordEncoder,
- formLoginProperties,
- userDetailsService
- );
- }
-
@Bean
@ConditionalOnMissingBean(IUserContextHolder.class)
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiAuthenticationFilter.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiAuthenticationFilter.java
similarity index 86%
rename from security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiAuthenticationFilter.java
rename to security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiAuthenticationFilter.java
index 27554ef..df7cb00 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiAuthenticationFilter.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiAuthenticationFilter.java
@@ -1,4 +1,4 @@
-package com.admin4j.framework.security.mult;
+package com.admin4j.framework.security.multi;
import com.admin4j.framework.security.properties.FormLoginProperties;
import com.admin4j.framework.security.properties.MultiAuthenticationProperties;
@@ -23,8 +23,8 @@
public class MultiAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
static final String DEFAULT_AUTH_TYPE = "";
- private MultiAuthenticationProperties multiAuthenticationProperties;
- private FormLoginProperties formLoginProperties;
+ private final MultiAuthenticationProperties multiAuthenticationProperties;
+ private final FormLoginProperties formLoginProperties;
public MultiAuthenticationFilter(MultiAuthenticationProperties multiAuthenticationProperties, FormLoginProperties formLoginProperties) {
@@ -51,7 +51,13 @@ public Authentication attemptAuthentication(HttpServletRequest request, HttpServ
return this.getAuthenticationManager().authenticate(token);
}
- private MultiAuthenticationToken obtainToken(HttpServletRequest request) {
+ /**
+ * 获取未认证的令牌
+ *
+ * @param request
+ * @return
+ */
+ protected MultiAuthenticationToken obtainToken(HttpServletRequest request) {
/**
* 获取授权方式
@@ -60,17 +66,13 @@ private MultiAuthenticationToken obtainToken(HttpServletRequest request) {
if (StringUtils.isBlank(authType)) {
- // 尝试去uri路径里面获取
+ // 尝试去uri路径里面获取 /login/phone
String requestURI = request.getRequestURI();
authType = StringUtils.substringAfter(requestURI, multiAuthenticationProperties.getLoginProcessingUrlPrefix());
}
String principal;
if (StringUtils.isBlank(authType)) {
- // if (!formLoginProperties.isEnable()) {
- // throw new AuthenticationServiceException(
- // "Authentication authType not find: " + request.getRequestURI());
- //}
// 默认开启了formLogin 获取默认的 username字段
authType = DEFAULT_AUTH_TYPE;
principal = request.getParameter(formLoginProperties.getUsernameParameter());
@@ -79,7 +81,6 @@ private MultiAuthenticationToken obtainToken(HttpServletRequest request) {
principal = request.getParameter(field);
}
-
return MultiAuthenticationToken.unauthenticated(authType, principal, request.getParameterMap());
}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiAuthenticationProvider.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiAuthenticationProvider.java
similarity index 95%
rename from security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiAuthenticationProvider.java
rename to security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiAuthenticationProvider.java
index e8201ce..c68ad85 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiAuthenticationProvider.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiAuthenticationProvider.java
@@ -1,4 +1,4 @@
-package com.admin4j.framework.security.mult;
+package com.admin4j.framework.security.multi;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -23,7 +23,6 @@ public class MultiAuthenticationProvider implements AuthenticationProvider {
private final List userDetailServices;
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
-
private UserDetailsChecker preAuthenticationChecks = new DefaultPreAuthenticationChecks();
private UserDetailsChecker postAuthenticationChecks = new DefaultPostAuthenticationChecks();
@@ -43,6 +42,7 @@ public boolean supports(Class> authentication) {
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
MultiAuthenticationToken authenticationToken = (MultiAuthenticationToken) authentication;
+ // 查找支持当前登录方式的 MultiUserDetailsService
MultiUserDetailsService userDetailService = null;
if (userDetailServices != null) {
for (MultiUserDetailsService item : userDetailServices) {
@@ -59,13 +59,16 @@ public Authentication authenticate(Authentication authentication) throws Authent
boolean b = userDetailService.preVerify(authenticationToken);
if (!b) {
- throw new InternalAuthenticationServiceException("Authentication failure");
+ throw new InternalAuthenticationServiceException("Authentication preVerify failure");
}
+ // 加载用户信息
UserDetails userDetails = userDetailService.loadUserByMultiToken((String) authenticationToken.getPrincipal());
+
+ // 检查用户信息
this.preAuthenticationChecks.check(userDetails);
- //生成一个认证成功 Authentication
+ // 生成一个认证成功 Authentication
MultiAuthenticationToken multiAuthenticationToken = new MultiAuthenticationToken(authenticationToken.getAuthType(), userDetails, userDetails.getAuthorities());
multiAuthenticationToken.setDetails(authenticationToken.getDetails());
multiAuthenticationToken.setAuthParameters(authenticationToken.getAuthParameters());
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiAuthenticationToken.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiAuthenticationToken.java
similarity index 98%
rename from security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiAuthenticationToken.java
rename to security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiAuthenticationToken.java
index 47820c6..487f7a4 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiAuthenticationToken.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiAuthenticationToken.java
@@ -1,4 +1,4 @@
-package com.admin4j.framework.security.mult;
+package com.admin4j.framework.security.multi;
import lombok.Getter;
import lombok.Setter;
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiCheckUsernamePasswordService.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiCheckUsernamePasswordService.java
similarity index 98%
rename from security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiCheckUsernamePasswordService.java
rename to security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiCheckUsernamePasswordService.java
index 17f5c57..6768059 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiCheckUsernamePasswordService.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiCheckUsernamePasswordService.java
@@ -1,4 +1,4 @@
-package com.admin4j.framework.security.mult;
+package com.admin4j.framework.security.multi;
import com.admin4j.common.Prioritized;
import com.admin4j.framework.security.properties.FormLoginProperties;
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiSecurityConfigurerAdapter.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiSecurityConfigurerAdapter.java
similarity index 66%
rename from security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiSecurityConfigurerAdapter.java
rename to security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiSecurityConfigurerAdapter.java
index 7c9f066..2844880 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiSecurityConfigurerAdapter.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiSecurityConfigurerAdapter.java
@@ -1,8 +1,8 @@
-package com.admin4j.framework.security.mult;
+package com.admin4j.framework.security.multi;
+import com.admin4j.framework.security.filter.JwtAuthenticationTokenFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@@ -15,14 +15,18 @@
public class MultiSecurityConfigurerAdapter extends AbstractHttpConfigurer {
private final MultiAuthenticationFilter multiAuthenticationFilter;
- private final AuthenticationProvider authenticationProvider;
+
+ private final AuthenticationManager authenticationManager;
+
+ private final JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
@Override
public void configure(HttpSecurity http) throws Exception {
-
- AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
+
multiAuthenticationFilter.setAuthenticationManager(authenticationManager);
- http.authenticationProvider(authenticationProvider)
+ http.authenticationManager(authenticationManager)
+ // 添加JWT filter
+ .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(multiAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiUserDetailsService.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiUserDetailsService.java
similarity index 96%
rename from security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiUserDetailsService.java
rename to security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiUserDetailsService.java
index 31798d2..9a79cb0 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/MultiUserDetailsService.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiUserDetailsService.java
@@ -1,4 +1,4 @@
-package com.admin4j.framework.security.mult;
+package com.admin4j.framework.security.multi;
import com.admin4j.common.Prioritized;
import org.springframework.security.core.userdetails.UserDetails;
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/UsernamePasswordUserDetailsService.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/UsernamePasswordUserDetailsService.java
similarity index 91%
rename from security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/UsernamePasswordUserDetailsService.java
rename to security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/UsernamePasswordUserDetailsService.java
index a97d135..71ddd5a 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/mult/UsernamePasswordUserDetailsService.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/UsernamePasswordUserDetailsService.java
@@ -1,4 +1,4 @@
-package com.admin4j.framework.security.mult;
+package com.admin4j.framework.security.multi;
import com.admin4j.framework.security.properties.FormLoginProperties;
import lombok.extern.slf4j.Slf4j;
@@ -15,7 +15,9 @@
@Slf4j
public class UsernamePasswordUserDetailsService extends MultiCheckUsernamePasswordService {
-
+ /**
+ * 兼容系统 原来的 UserDetailsService
+ */
private final UserDetailsService userDetailsService;
public UsernamePasswordUserDetailsService(PasswordEncoder passwordEncoder, FormLoginProperties formLoginProperties, UserDetailsService userDetailsService) {
@@ -32,6 +34,8 @@ public UsernamePasswordUserDetailsService(PasswordEncoder passwordEncoder, FormL
*/
@Override
public UserDetails loadUserByMultiToken(String multiToken) {
+
+
return userDetailsService.loadUserByUsername(multiToken);
}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/properties/CorsProperties.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/properties/CorsProperties.java
index 148a2f0..a60510c 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/properties/CorsProperties.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/properties/CorsProperties.java
@@ -31,5 +31,5 @@ public class CorsProperties {
/**
* 是否允许客户端带cookie
*/
- private boolean allowCredentials = true;
+ private boolean allowCredentials = false;
}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/properties/FormLoginProperties.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/properties/FormLoginProperties.java
index 711c8e7..83adf0c 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/properties/FormLoginProperties.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/properties/FormLoginProperties.java
@@ -16,6 +16,10 @@ public class FormLoginProperties {
* 开启form 处理 url
*/
private String loginProcessingUrl = "/login";
+ /**
+ * 退出处理url
+ */
+ private String logOutProcessingUrl = "/logout";
/**
* 密码字段名
*/
@@ -24,4 +28,8 @@ public class FormLoginProperties {
* 账号字段名
*/
private String usernameParameter = "username";
+ /**
+ * 开启默认的表单登录
+ */
+ private boolean enable = true;
}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/properties/IgnoringUrlProperties.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/properties/IgnoringUrlProperties.java
index a66da49..c172df5 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/properties/IgnoringUrlProperties.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/properties/IgnoringUrlProperties.java
@@ -4,7 +4,7 @@
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
- * 忽略url 配置文件
+ * 根据配置文件 忽略url
*
* @author andanyang
* @since 2023/3/24 17:00
@@ -14,7 +14,7 @@
public class IgnoringUrlProperties {
/**
- * 包含所有请求类型的路径
+ * 包含所有请求类型的路径,不考虑请求方法
*/
private String[] uris;
/**
diff --git a/security-spring-boot-starter/src/main/resources/META-INF/spring.factories b/security-spring-boot-starter/src/main/resources/META-INF/spring.factories
index 280eadb..78953a9 100644
--- a/security-spring-boot-starter/src/main/resources/META-INF/spring.factories
+++ b/security-spring-boot-starter/src/main/resources/META-INF/spring.factories
@@ -6,7 +6,9 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.admin4j.framework.security.configuration.SecurityConfiguration, \
com.admin4j.framework.security.configuration.SecurityHandlerConfiguration, \
com.admin4j.framework.security.configuration.CorsConfiguration, \
- com.admin4j.framework.security.configuration.UserTokenServiceConfiguration
+ com.admin4j.framework.security.configuration.UserTokenServiceConfiguration, \
+ com.admin4j.framework.security.configuration.MultiAuthenticationManagerAutoConfiguration, \
+ com.admin4j.framework.security.configuration.MultiAuthenticationAutoConfiguration
From e27f1105c9f331ab04889bd8cb548810086a788c Mon Sep 17 00:00:00 2001
From: andanyang <1218853253@qq.com>
Date: Mon, 18 Dec 2023 17:46:38 +0800
Subject: [PATCH 19/30] =?UTF-8?q?feat(security):=20security=20Authenticati?=
=?UTF-8?q?onManager=20=E4=BB=A3=E7=A0=81=E9=87=8D=E6=96=B0=E6=A2=B3?=
=?UTF-8?q?=E7=90=86?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
security-spring-boot-starter/README.md | 5 +++++
.../MultiAuthenticationManagerAutoConfiguration.java | 1 -
2 files changed, 5 insertions(+), 1 deletion(-)
diff --git a/security-spring-boot-starter/README.md b/security-spring-boot-starter/README.md
index 9f917b2..5cde5c0 100644
--- a/security-spring-boot-starter/README.md
+++ b/security-spring-boot-starter/README.md
@@ -1,5 +1,10 @@
# admin security
+## Features
+
+- 多渠道登录
+- 一个注解/一个配置,解决匿名url访问(忽略认证)
+
## USAGES
1. 引入 pom
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/MultiAuthenticationManagerAutoConfiguration.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/MultiAuthenticationManagerAutoConfiguration.java
index 641ce57..6e334c9 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/MultiAuthenticationManagerAutoConfiguration.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/MultiAuthenticationManagerAutoConfiguration.java
@@ -69,5 +69,4 @@ public AuthenticationManager authenticationManager(@Autowired(required = false)
return new ProviderManager(new MultiAuthenticationProvider(userDetailServices));
}
-
}
From 44dfa856496d2f543e7d47f9d89c18991a59b5f3 Mon Sep 17 00:00:00 2001
From: andanyang <1218853253@qq.com>
Date: Mon, 18 Dec 2023 17:48:37 +0800
Subject: [PATCH 20/30] =?UTF-8?q?feat(security):=20security=20Authenticati?=
=?UTF-8?q?onManager=20=E4=BB=A3=E7=A0=81=E9=87=8D=E6=96=B0=E6=A2=B3?=
=?UTF-8?q?=E7=90=86?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
admin4j-dependencies/pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/admin4j-dependencies/pom.xml b/admin4j-dependencies/pom.xml
index e1f304d..ed76042 100644
--- a/admin4j-dependencies/pom.xml
+++ b/admin4j-dependencies/pom.xml
@@ -155,7 +155,7 @@
com.admin4j.framework
security-spring-boot-starter
- 0.9.3-SNAPSHOT
+ 0.9.4-SNAPSHOT
com.admin4j.framework
From ddaeb9322339dcdaf85ecd488836580140faefd6 Mon Sep 17 00:00:00 2001
From: andanyang <1218853253@qq.com>
Date: Tue, 19 Dec 2023 09:52:50 +0800
Subject: [PATCH 21/30] feat(AuthenticationHandler): AuthenticationHandler
rename
---
...Result.java => AuthenticationHandler.java} | 4 ++-
.../configuration/SecurityConfiguration.java | 2 +-
.../SecurityHandlerConfiguration.java | 28 +++++++++----------
.../filter/JwtAuthenticationTokenFilter.java | 6 ++--
...java => DefaultAuthenticationHandler.java} | 4 +--
.../handler/RestAccessDeniedHandler.java | 6 ++--
.../handler/RestAuthenticationEntryPoint.java | 8 +++---
.../RestAuthenticationFailureHandler.java | 6 ++--
.../RestAuthenticationSuccessHandler.java | 9 ++----
.../handler/RestLogoutSuccessHandler.java | 6 ++--
10 files changed, 39 insertions(+), 40 deletions(-)
rename security-spring-boot-starter/src/main/java/com/admin4j/framework/security/{AuthenticationResult.java => AuthenticationHandler.java} (94%)
rename security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/{DefaultAuthenticationResult.java => DefaultAuthenticationHandler.java} (96%)
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/AuthenticationResult.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/AuthenticationHandler.java
similarity index 94%
rename from security-spring-boot-starter/src/main/java/com/admin4j/framework/security/AuthenticationResult.java
rename to security-spring-boot-starter/src/main/java/com/admin4j/framework/security/AuthenticationHandler.java
index 2b1f9f5..5542dd9 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/AuthenticationResult.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/AuthenticationHandler.java
@@ -8,10 +8,12 @@
import javax.servlet.http.HttpServletResponse;
/**
+ * 认证成功结果回调处理
+ *
* @author andanyang
* @since 2023/5/31 17:57
*/
-public interface AuthenticationResult {
+public interface AuthenticationHandler {
/**
* 认证成功回调
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityConfiguration.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityConfiguration.java
index 20d9542..1f530c3 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityConfiguration.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityConfiguration.java
@@ -145,7 +145,7 @@ public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Excepti
if (actuatorFilter != null) {
httpSecurity.addFilterBefore(actuatorFilter, UsernamePasswordAuthenticationFilter.class);
}
-
+
// 多渠道登录
if (multiSecurityConfigurerAdapter != null) {
httpSecurity.apply(multiSecurityConfigurerAdapter);
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityHandlerConfiguration.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityHandlerConfiguration.java
index 5aa4f5e..8734f9c 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityHandlerConfiguration.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityHandlerConfiguration.java
@@ -1,6 +1,6 @@
package com.admin4j.framework.security.configuration;
-import com.admin4j.framework.security.AuthenticationResult;
+import com.admin4j.framework.security.AuthenticationHandler;
import com.admin4j.framework.security.UserTokenService;
import com.admin4j.framework.security.handler.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
@@ -15,39 +15,39 @@
public class SecurityHandlerConfiguration {
@Bean
- @ConditionalOnMissingBean({AuthenticationResult.class})
- public AuthenticationResult authenticationResult(UserTokenService userTokenService) {
- return new DefaultAuthenticationResult(userTokenService);
+ @ConditionalOnMissingBean({AuthenticationHandler.class})
+ public AuthenticationHandler authenticationResult(UserTokenService userTokenService) {
+ return new DefaultAuthenticationHandler(userTokenService);
}
@Bean
@ConditionalOnMissingBean(AuthenticationEntryPoint.class)
- public AuthenticationEntryPoint authenticationEntryPoint(AuthenticationResult authenticationResult) {
- return new RestAuthenticationEntryPoint(authenticationResult);
+ public AuthenticationEntryPoint authenticationEntryPoint(AuthenticationHandler authenticationHandler) {
+ return new RestAuthenticationEntryPoint(authenticationHandler);
}
@Bean
@ConditionalOnMissingBean(AuthenticationFailureHandler.class)
- public AuthenticationFailureHandler authenticationFailureHandler(AuthenticationResult authenticationResult) {
- return new RestAuthenticationFailureHandler(authenticationResult);
+ public AuthenticationFailureHandler authenticationFailureHandler(AuthenticationHandler authenticationHandler) {
+ return new RestAuthenticationFailureHandler(authenticationHandler);
}
@Bean
@ConditionalOnMissingBean(AuthenticationSuccessHandler.class)
- public AuthenticationSuccessHandler authenticationSuccessHandler(AuthenticationResult authenticationResult) {
- return new RestAuthenticationSuccessHandler(authenticationResult);
+ public AuthenticationSuccessHandler authenticationSuccessHandler(AuthenticationHandler authenticationHandler) {
+ return new RestAuthenticationSuccessHandler(authenticationHandler);
}
@Bean
@ConditionalOnMissingBean(AccessDeniedHandler.class)
- public AccessDeniedHandler accessDeniedHandler(AuthenticationResult authenticationResult) {
- return new RestAccessDeniedHandler(authenticationResult);
+ public AccessDeniedHandler accessDeniedHandler(AuthenticationHandler authenticationHandler) {
+ return new RestAccessDeniedHandler(authenticationHandler);
}
@Bean
@ConditionalOnMissingBean(LogoutSuccessHandler.class)
- public LogoutSuccessHandler logoutSuccessHandler(AuthenticationResult authenticationResult) {
- return new RestLogoutSuccessHandler(authenticationResult);
+ public LogoutSuccessHandler logoutSuccessHandler(AuthenticationHandler authenticationHandler) {
+ return new RestLogoutSuccessHandler(authenticationHandler);
}
@Bean
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/filter/JwtAuthenticationTokenFilter.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/filter/JwtAuthenticationTokenFilter.java
index 5f3102b..061b0c6 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/filter/JwtAuthenticationTokenFilter.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/filter/JwtAuthenticationTokenFilter.java
@@ -2,7 +2,7 @@
import com.admin4j.common.pojo.AuthenticationUser;
import com.admin4j.common.util.UserContextUtil;
-import com.admin4j.framework.security.AuthenticationResult;
+import com.admin4j.framework.security.AuthenticationHandler;
import com.admin4j.framework.security.UserTokenService;
import com.admin4j.framework.security.exception.JwtTokenExpiredException;
import com.admin4j.framework.security.factory.AuthenticationUserFactory;
@@ -35,7 +35,7 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
//@Autowired
// UserDetailsService userDetailsService;
@Autowired
- AuthenticationResult authenticationResult;
+ AuthenticationHandler authenticationHandler;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
@@ -64,7 +64,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
}
} catch (Exception e) {
log.error("authenticationEntryPoint {}", e.getMessage(), e);
- authenticationResult.authenticationEntryPoint(request, response, new JwtTokenExpiredException(e.getMessage(), e));
+ authenticationHandler.authenticationEntryPoint(request, response, new JwtTokenExpiredException(e.getMessage(), e));
return;
}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/DefaultAuthenticationResult.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/DefaultAuthenticationHandler.java
similarity index 96%
rename from security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/DefaultAuthenticationResult.java
rename to security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/DefaultAuthenticationHandler.java
index 50ff672..92b8ae6 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/DefaultAuthenticationResult.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/DefaultAuthenticationHandler.java
@@ -6,7 +6,7 @@
import com.admin4j.common.pojo.SimpleResponse;
import com.admin4j.common.util.ServletUtils;
import com.admin4j.common.util.UserContextUtil;
-import com.admin4j.framework.security.AuthenticationResult;
+import com.admin4j.framework.security.AuthenticationHandler;
import com.admin4j.framework.security.UserTokenService;
import com.admin4j.framework.security.event.AuthenticationSuccessEvent;
import com.admin4j.framework.security.factory.AuthenticationUserFactory;
@@ -30,7 +30,7 @@
*/
@Slf4j
@RequiredArgsConstructor
-public class DefaultAuthenticationResult implements AuthenticationResult {
+public class DefaultAuthenticationHandler implements AuthenticationHandler {
protected static final IResponse FAIL_AUTH_FORBIDDEN = new SimpleResponse(ResponseEnum.FAIL_AUTH_FORBIDDEN);
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestAccessDeniedHandler.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestAccessDeniedHandler.java
index 9509d1e..2ba62a7 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestAccessDeniedHandler.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestAccessDeniedHandler.java
@@ -1,6 +1,6 @@
package com.admin4j.framework.security.handler;
-import com.admin4j.framework.security.AuthenticationResult;
+import com.admin4j.framework.security.AuthenticationHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
@@ -18,7 +18,7 @@
@RequiredArgsConstructor
public class RestAccessDeniedHandler implements AccessDeniedHandler {
- final AuthenticationResult authenticationResult;
+ final AuthenticationHandler authenticationHandler;
@Override
public void handle(
@@ -26,6 +26,6 @@ public void handle(
throws IOException, ServletException {
- authenticationResult.accessDeniedHandler(httpServletRequest, response, e);
+ authenticationHandler.accessDeniedHandler(httpServletRequest, response, e);
}
}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestAuthenticationEntryPoint.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestAuthenticationEntryPoint.java
index e532365..3344249 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestAuthenticationEntryPoint.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestAuthenticationEntryPoint.java
@@ -1,6 +1,6 @@
package com.admin4j.framework.security.handler;
-import com.admin4j.framework.security.AuthenticationResult;
+import com.admin4j.framework.security.AuthenticationHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
@@ -19,8 +19,8 @@
@Slf4j
@RequiredArgsConstructor
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
-
- private final AuthenticationResult authenticationResult;
+
+ private final AuthenticationHandler authenticationHandler;
@Override
public void commence(
@@ -29,6 +29,6 @@ public void commence(
AuthenticationException authException)
throws IOException, ServletException {
- authenticationResult.authenticationEntryPoint(request, response, authException);
+ authenticationHandler.authenticationEntryPoint(request, response, authException);
}
}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestAuthenticationFailureHandler.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestAuthenticationFailureHandler.java
index 6f62f67..2bb13f3 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestAuthenticationFailureHandler.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestAuthenticationFailureHandler.java
@@ -1,6 +1,6 @@
package com.admin4j.framework.security.handler;
-import com.admin4j.framework.security.AuthenticationResult;
+import com.admin4j.framework.security.AuthenticationHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
@@ -17,10 +17,10 @@
@RequiredArgsConstructor
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {
- final AuthenticationResult authenticationResult;
+ final AuthenticationHandler authenticationHandler;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
- authenticationResult.onAuthenticationFailure(request, response, exception);
+ authenticationHandler.onAuthenticationFailure(request, response, exception);
}
}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestAuthenticationSuccessHandler.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestAuthenticationSuccessHandler.java
index 99bcfb7..d57c340 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestAuthenticationSuccessHandler.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestAuthenticationSuccessHandler.java
@@ -1,6 +1,6 @@
package com.admin4j.framework.security.handler;
-import com.admin4j.framework.security.AuthenticationResult;
+import com.admin4j.framework.security.AuthenticationHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
@@ -19,6 +19,7 @@
*/
@RequiredArgsConstructor
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler, ApplicationContextAware {
+ final AuthenticationHandler authenticationHandler;
private ApplicationContext applicationContext;
@Override
@@ -26,14 +27,10 @@ public void setApplicationContext(ApplicationContext applicationContext) throws
this.applicationContext = applicationContext;
}
-
- final AuthenticationResult authenticationResult;
-
-
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
- authenticationResult.onAuthenticationSuccess(request, response, authentication);
+ authenticationHandler.onAuthenticationSuccess(request, response, authentication);
}
}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestLogoutSuccessHandler.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestLogoutSuccessHandler.java
index bf250b9..d406a57 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestLogoutSuccessHandler.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/RestLogoutSuccessHandler.java
@@ -1,6 +1,6 @@
package com.admin4j.framework.security.handler;
-import com.admin4j.framework.security.AuthenticationResult;
+import com.admin4j.framework.security.AuthenticationHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
@@ -17,11 +17,11 @@
@RequiredArgsConstructor
public class RestLogoutSuccessHandler implements LogoutSuccessHandler {
- final AuthenticationResult authenticationResult;
+ final AuthenticationHandler authenticationHandler;
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
- authenticationResult.onLogoutSuccess(request, response, authentication);
+ authenticationHandler.onLogoutSuccess(request, response, authentication);
}
}
From 86639a442b184988bc04f9040dc68725c570c35e Mon Sep 17 00:00:00 2001
From: andanyang <1218853253@qq.com>
Date: Tue, 19 Dec 2023 14:43:10 +0800
Subject: [PATCH 22/30] =?UTF-8?q?feat(security):=20=E6=B7=BB=E5=8A=A0?=
=?UTF-8?q?=E8=87=AA=E5=AE=9A=E4=B9=89=E5=8A=A8=E6=80=81=E6=9D=83=E9=99=90?=
=?UTF-8?q?=20PermissionAuthorizationManager?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
security-spring-boot-starter/README.md | 1 +
security-spring-boot-starter/pom.xml | 2 +-
.../authorization/IPermissionUriService.java | 26 ++++
.../PermissionAuthorizationManager.java | 114 ++++++++++++++++++
...uthenticationManagerAutoConfiguration.java | 2 +-
.../PermissionAutoConfiguration.java | 22 ++++
.../configuration/SecurityConfiguration.java | 51 +++++---
.../multi/MultiAuthenticationFilter.java | 2 +-
8 files changed, 199 insertions(+), 21 deletions(-)
create mode 100644 security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUriService.java
create mode 100644 security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java
create mode 100644 security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/PermissionAutoConfiguration.java
diff --git a/security-spring-boot-starter/README.md b/security-spring-boot-starter/README.md
index 5cde5c0..90a0a4a 100644
--- a/security-spring-boot-starter/README.md
+++ b/security-spring-boot-starter/README.md
@@ -4,6 +4,7 @@
- 多渠道登录
- 一个注解/一个配置,解决匿名url访问(忽略认证)
+- 基于数据库的动态权限
## USAGES
diff --git a/security-spring-boot-starter/pom.xml b/security-spring-boot-starter/pom.xml
index a491f78..142144f 100644
--- a/security-spring-boot-starter/pom.xml
+++ b/security-spring-boot-starter/pom.xml
@@ -10,7 +10,7 @@
com.admin4j.framework
security-spring-boot-starter
jar
- 0.9.4-SNAPSHOT
+ 0.9.5-SNAPSHOT
security-spring-boot-starter
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUriService.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUriService.java
new file mode 100644
index 0000000..8ce5e16
--- /dev/null
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUriService.java
@@ -0,0 +1,26 @@
+package com.admin4j.framework.security.authorization;
+
+import java.util.List;
+
+/**
+ * 权限uri 服务
+ *
+ * @author andanyang
+ * @since 2023/12/19 14:34
+ */
+public interface IPermissionUriService {
+
+ /**
+ * 获取 系统 所有的 PermissionUri
+ *
+ * @return
+ */
+ List allPermissionUri();
+
+ /**
+ * 当前用户拥有的权限
+ *
+ * @return
+ */
+ List getMyPermissionUrls();
+}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java
new file mode 100644
index 0000000..cff3395
--- /dev/null
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java
@@ -0,0 +1,114 @@
+package com.admin4j.framework.security.authorization;
+
+import lombok.RequiredArgsConstructor;
+import org.springframework.security.authorization.AuthorizationDecision;
+import org.springframework.security.authorization.AuthorizationManager;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
+import org.springframework.util.AntPathMatcher;
+
+import java.util.Collection;
+import java.util.function.Supplier;
+
+/**
+ * 自定义数据权限(授权)处理
+ * 被授 AuthorizationFilter 调用,负责做出最终的访问控制决定
+ *
+ * @author andanyang
+ * @since 2023/12/19 9:53
+ */
+@RequiredArgsConstructor
+public class PermissionAuthorizationManager implements AuthorizationManager {
+
+ /**
+ * 有权限
+ */
+ protected static final AuthorizationDecision GRANTED = new AuthorizationDecision(true);
+ /**
+ * 没有权限
+ */
+ protected static final AuthorizationDecision UN_AUTHORIZED = new AuthorizationDecision(false);
+
+ protected final IPermissionUriService permissionUriService;
+
+ protected AntPathMatcher antPathMatcher = new AntPathMatcher();
+
+ /**
+ * Determines if access is granted for a specific authentication and object.
+ *
+ * @param authentication the {@link Supplier} of the {@link Authentication} to check
+ * @param object the {@link T} object to check
+ * @return an {@link AuthorizationDecision} or null if no decision could be made
+ */
+ @Override
+ public AuthorizationDecision check(Supplier authentication, RequestAuthorizationContext object) {
+
+ // 获取当前请求的 URL 地址
+ String requestURI = object.getRequest().getRequestURI();
+ boolean matchPermission = matchPermission(requestURI);
+ if (matchPermission) {
+ return GRANTED;
+ }
+
+ // 沒有匹配到, 查看当前 requestURI 是否需要权限控制
+ return urlNeedPermission(requestURI) ? UN_AUTHORIZED : GRANTED;
+ }
+
+ /**
+ * url 是否需要授权
+ * TODO 放在 service 立马
+ *
+ * @return
+ */
+ public boolean urlNeedPermission(String requestURI) {
+
+ Collection allPermissionUrls = getAllPermissionUrls();
+ for (String url : allPermissionUrls) {
+ if (antPathMatcher.match(url, requestURI)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * 当前用户是否可以匹配到访问该url权限
+ *
+ * @param requestURI
+ * @return
+ */
+ public boolean matchPermission(String requestURI) {
+ Collection permissionUrls = getPermissionUrls();
+
+ if (permissionUrls == null || permissionUrls.isEmpty()) {
+ return false;
+ }
+
+ for (String url : permissionUrls) {
+ if (antPathMatcher.match(url, requestURI)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * 当前用户拥有的权限
+ *
+ * @return
+ */
+ public Collection getPermissionUrls() {
+
+ return permissionUriService.getMyPermissionUrls();
+ }
+
+
+ /**
+ * 获取全部权限
+ *
+ * @return
+ */
+ protected Collection getAllPermissionUrls() {
+ return permissionUriService.allPermissionUri();
+ }
+}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/MultiAuthenticationManagerAutoConfiguration.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/MultiAuthenticationManagerAutoConfiguration.java
index 6e334c9..7554de7 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/MultiAuthenticationManagerAutoConfiguration.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/MultiAuthenticationManagerAutoConfiguration.java
@@ -50,7 +50,7 @@ public MultiUserDetailsService usernamePasswordUserDetailsService(
/**
- * 获取 AuthenticationManager
+ * 获取 PermissionAuthorizationManager
*
* 或者:
*
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/PermissionAutoConfiguration.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/PermissionAutoConfiguration.java
new file mode 100644
index 0000000..b0f49f5
--- /dev/null
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/PermissionAutoConfiguration.java
@@ -0,0 +1,22 @@
+package com.admin4j.framework.security.configuration;
+
+import com.admin4j.framework.security.authorization.IPermissionUriService;
+import com.admin4j.framework.security.authorization.PermissionAuthorizationManager;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.context.annotation.Bean;
+
+/**
+ * @author andanyang
+ * @since 2023/12/19 14:40
+ */
+@ConditionalOnBean(IPermissionUriService.class)
+@ConditionalOnMissingBean(PermissionAuthorizationManager.class)
+public class PermissionAutoConfiguration {
+
+ @Bean
+ public PermissionAuthorizationManager permissionAuthorizationManager(IPermissionUriService permissionUriService) {
+
+ return new PermissionAuthorizationManager(permissionUriService);
+ }
+}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityConfiguration.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityConfiguration.java
index 1f530c3..d9bb4b5 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityConfiguration.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityConfiguration.java
@@ -1,6 +1,7 @@
package com.admin4j.framework.security.configuration;
import com.admin4j.framework.security.ISecurityIgnoringUrl;
+import com.admin4j.framework.security.authorization.PermissionAuthorizationManager;
import com.admin4j.framework.security.filter.ActuatorFilter;
import com.admin4j.framework.security.ignoringUrl.AnonymousAccessUrl;
import com.admin4j.framework.security.multi.MultiSecurityConfigurerAdapter;
@@ -16,8 +17,9 @@
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
+import org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
+import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
@@ -33,7 +35,7 @@
/**
* TODO 需要注入,取消 UserDetailsServiceAutoConfiguration 开启
- * value = { AuthenticationManager.class, AuthenticationProvider.class, UserDetailsService.class,
+ * value = { PermissionAuthorizationManager.class, AuthenticationProvider.class, UserDetailsService.class,
* AuthenticationManagerResolver.class },
*
* @author andanyang
@@ -79,7 +81,8 @@ public class SecurityConfiguration {
CorsFilter corsFilter;
@Autowired(required = false)
MultiSecurityConfigurerAdapter multiSecurityConfigurerAdapter;
-
+ @Autowired(required = false)
+ PermissionAuthorizationManager permissionAuthorizationManager;
/**
* 取消ROLE_前缀
*/
@@ -131,11 +134,6 @@ public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Excepti
// 添加Logout filter
httpSecurity.logout().logoutUrl(formLoginProperties.getLogOutProcessingUrl()).permitAll().logoutSuccessHandler(logoutSuccessHandler);
- // 授权请求配置
- // 忽略URl配置
- ignoringRequestMatcherRegistry(httpSecurity.authorizeRequests());
- // 除上面外的所有请求全部需要鉴权认证;其他路径必须验证
- httpSecurity.authorizeRequests().anyRequest().authenticated();
// 添加CORS filter
if (corsFilter != null) {
@@ -160,6 +158,22 @@ public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Excepti
.permitAll();
}
+ // 授权请求配置 authorizeHttpRequests(6.0 新版) authorizeRequests(旧版) 区别
+ // httpSecurity.authorizeRequests().anyRequest().authenticated();
+ httpSecurity.authorizeHttpRequests(register -> {
+
+ // 忽略URl配置
+ ignoringRequestMatcherRegistry(register);
+ if (permissionAuthorizationManager != null) {
+ // 自定义授权
+ register.anyRequest().access(permissionAuthorizationManager);
+ } else {
+ // 除上面外的所有请求全部需要鉴权认证;其他路径必须验证
+ register.anyRequest().authenticated();
+ }
+
+ });
+
return httpSecurity.build();
}
@@ -167,7 +181,8 @@ public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Excepti
/**
* 忽略URl配置
*/
- private void ignoringRequestMatcherRegistry(ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry expressionInterceptUrlRegistry) {
+ private void ignoringRequestMatcherRegistry(AbstractRequestMatcherRegistry.AuthorizedUrl> matcherRegistry) {
+
if (securityIgnoringUrls != null && !securityIgnoringUrls.isEmpty()) {
securityIgnoringUrls.forEach(url -> {
@@ -177,9 +192,9 @@ private void ignoringRequestMatcherRegistry(ExpressionUrlAuthorizationConfigurer
}
if (url.support() == null) {
- expressionInterceptUrlRegistry.antMatchers(url.ignoringUrls()).permitAll();
+ matcherRegistry.mvcMatchers(url.ignoringUrls()).permitAll();
} else {
- expressionInterceptUrlRegistry.antMatchers(url.support(), url.ignoringUrls()).permitAll();
+ matcherRegistry.antMatchers(url.support(), url.ignoringUrls()).permitAll();
}
});
}
@@ -187,23 +202,23 @@ private void ignoringRequestMatcherRegistry(ExpressionUrlAuthorizationConfigurer
if (ignoringUrlProperties != null) {
if (ignoringUrlProperties.getUris() != null && ignoringUrlProperties.getUris().length > 0) {
- expressionInterceptUrlRegistry.antMatchers(ignoringUrlProperties.getUris()).permitAll();
+ matcherRegistry.antMatchers(ignoringUrlProperties.getUris()).permitAll();
}
if (ignoringUrlProperties.getGet() != null && ignoringUrlProperties.getGet().length > 0) {
- expressionInterceptUrlRegistry.antMatchers(HttpMethod.GET, ignoringUrlProperties.getGet()).permitAll();
+ matcherRegistry.antMatchers(HttpMethod.GET, ignoringUrlProperties.getGet()).permitAll();
}
if (ignoringUrlProperties.getPost() != null && ignoringUrlProperties.getPost().length > 0) {
- expressionInterceptUrlRegistry.antMatchers(HttpMethod.POST, ignoringUrlProperties.getPost()).permitAll();
+ matcherRegistry.antMatchers(HttpMethod.POST, ignoringUrlProperties.getPost()).permitAll();
}
if (ignoringUrlProperties.getPut() != null && ignoringUrlProperties.getPut().length > 0) {
- expressionInterceptUrlRegistry.antMatchers(HttpMethod.PUT, ignoringUrlProperties.getPut()).permitAll();
+ matcherRegistry.antMatchers(HttpMethod.PUT, ignoringUrlProperties.getPut()).permitAll();
}
if (ignoringUrlProperties.getPatch() != null && ignoringUrlProperties.getPatch().length > 0) {
- expressionInterceptUrlRegistry.antMatchers(HttpMethod.PATCH, ignoringUrlProperties.getPatch()).permitAll();
+ matcherRegistry.antMatchers(HttpMethod.PATCH, ignoringUrlProperties.getPatch()).permitAll();
}
if (ignoringUrlProperties.getDelete() != null && ignoringUrlProperties.getDelete().length > 0) {
- expressionInterceptUrlRegistry.antMatchers(HttpMethod.DELETE, ignoringUrlProperties.getDelete()).permitAll();
+ matcherRegistry.antMatchers(HttpMethod.DELETE, ignoringUrlProperties.getDelete()).permitAll();
}
}
@@ -213,7 +228,7 @@ private void ignoringRequestMatcherRegistry(ExpressionUrlAuthorizationConfigurer
Map anonymousUrl = anonymousAccessUrl.getAnonymousUrl();
anonymousUrl.keySet().forEach(i -> {
- expressionInterceptUrlRegistry.antMatchers(i, anonymousUrl.get(i)).permitAll();
+ matcherRegistry.antMatchers(i, anonymousUrl.get(i)).permitAll();
});
}
}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiAuthenticationFilter.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiAuthenticationFilter.java
index df7cb00..3fe0cfe 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiAuthenticationFilter.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/multi/MultiAuthenticationFilter.java
@@ -47,7 +47,7 @@ public Authentication attemptAuthentication(HttpServletRequest request, HttpServ
MultiAuthenticationToken token = obtainToken(request);
setDetails(request, token);
- // 匹配成功交给 AuthenticationManager 去认证
+ // 匹配成功交给 PermissionAuthorizationManager 去认证
return this.getAuthenticationManager().authenticate(token);
}
From 7cc902e42b8a78c638b0636ecb1410e12a23ccf3 Mon Sep 17 00:00:00 2001
From: andanyang <1218853253@qq.com>
Date: Tue, 19 Dec 2023 14:45:34 +0800
Subject: [PATCH 23/30] =?UTF-8?q?feat(security):=20=E6=B7=BB=E5=8A=A0?=
=?UTF-8?q?=E8=87=AA=E5=AE=9A=E4=B9=89=E5=8A=A8=E6=80=81=E6=9D=83=E9=99=90?=
=?UTF-8?q?=20PermissionAuthorizationManager?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../security/authorization/PermissionAuthorizationManager.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java
index cff3395..944a94a 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java
@@ -36,7 +36,7 @@ public class PermissionAuthorizationManager implements AuthorizationManager
Date: Tue, 19 Dec 2023 14:49:54 +0800
Subject: [PATCH 24/30] =?UTF-8?q?feat(security):=20=E6=B7=BB=E5=8A=A0?=
=?UTF-8?q?=E8=87=AA=E5=AE=9A=E4=B9=89=E5=8A=A8=E6=80=81=E6=9D=83=E9=99=90?=
=?UTF-8?q?=20PermissionAuthorizationManager?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../src/main/resources/META-INF/spring.factories | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/security-spring-boot-starter/src/main/resources/META-INF/spring.factories b/security-spring-boot-starter/src/main/resources/META-INF/spring.factories
index 78953a9..3a93ddc 100644
--- a/security-spring-boot-starter/src/main/resources/META-INF/spring.factories
+++ b/security-spring-boot-starter/src/main/resources/META-INF/spring.factories
@@ -8,7 +8,8 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.admin4j.framework.security.configuration.CorsConfiguration, \
com.admin4j.framework.security.configuration.UserTokenServiceConfiguration, \
com.admin4j.framework.security.configuration.MultiAuthenticationManagerAutoConfiguration, \
- com.admin4j.framework.security.configuration.MultiAuthenticationAutoConfiguration
+ com.admin4j.framework.security.configuration.MultiAuthenticationAutoConfiguration, \
+ com.admin4j.framework.security.configuration.PermissionAutoConfiguration
From eccd4579d80db680821dd1c16f09ae9fc1a5796f Mon Sep 17 00:00:00 2001
From: andanyang <1218853253@qq.com>
Date: Tue, 19 Dec 2023 15:48:21 +0800
Subject: [PATCH 25/30] =?UTF-8?q?feat(security):=20SecurityUserContextHold?=
=?UTF-8?q?er=20=E4=BB=A3=E7=A0=81=E4=BC=98=E5=8C=96?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
admin4j-common-spring-web/pom.xml | 22 +++-
.../config/UserContextAutoConfiguration.java | 43 +++++++
.../common/config/UserContextConfig.java | 24 ----
.../impl}/SimpleUserContextHolder.java | 42 ++++---
.../main/resources/META-INF/spring.factories | 2 +-
admin4j-dependencies/pom.xml | 2 +-
pom.xml | 4 +-
.../context/SecurityUserContextHolder.java | 119 +-----------------
web-spring-boot-starter/pom.xml | 5 -
.../UserContextAutoConfiguration.java | 26 ----
.../main/resources/META-INF/spring.factories | 3 +-
11 files changed, 93 insertions(+), 199 deletions(-)
create mode 100644 admin4j-common-spring-web/src/main/java/com/admin4j/common/config/UserContextAutoConfiguration.java
delete mode 100644 admin4j-common-spring-web/src/main/java/com/admin4j/common/config/UserContextConfig.java
rename {web-spring-boot-starter/src/main/java/com/admin4j/framework/web => admin4j-common-spring-web/src/main/java/com/admin4j/common/service/impl}/SimpleUserContextHolder.java (92%)
delete mode 100644 web-spring-boot-starter/src/main/java/com/admin4j/framework/web/autoconfigure/UserContextAutoConfiguration.java
diff --git a/admin4j-common-spring-web/pom.xml b/admin4j-common-spring-web/pom.xml
index b072a6a..bbf0a85 100644
--- a/admin4j-common-spring-web/pom.xml
+++ b/admin4j-common-spring-web/pom.xml
@@ -1,6 +1,6 @@
-
4.0.0
@@ -11,6 +11,7 @@
com.admin4j.common
admin4j-common-spring-web
+ 0.9.3-SNAPSHOT
与业务无关的工具类库
@@ -20,9 +21,16 @@
+
+
+ com.alibaba
+ transmittable-thread-local
+ provided
+
org.springframework.boot
spring-boot
+ provided
io.swagger
@@ -71,5 +79,15 @@
hibernate-validator
provided
+
+ org.springframework.boot
+ spring-boot-autoconfigure
+ provided
+
+
+ org.springframework.boot
+ spring-boot-autoconfigure-processor
+ provided
+
\ No newline at end of file
diff --git a/admin4j-common-spring-web/src/main/java/com/admin4j/common/config/UserContextAutoConfiguration.java b/admin4j-common-spring-web/src/main/java/com/admin4j/common/config/UserContextAutoConfiguration.java
new file mode 100644
index 0000000..1a650af
--- /dev/null
+++ b/admin4j-common-spring-web/src/main/java/com/admin4j/common/config/UserContextAutoConfiguration.java
@@ -0,0 +1,43 @@
+package com.admin4j.common.config;
+
+import com.admin4j.common.constant.WebConstant;
+import com.admin4j.common.service.IUserContextHolder;
+import com.admin4j.common.service.impl.SimpleUserContextHolder;
+import com.admin4j.common.util.UserContextUtil;
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * @author andanyang
+ * @since 2023/9/15 9:19
+ */
+@Configuration
+@AutoConfigureOrder(WebConstant.IUserContextHolderOrder + 6)
+public class UserContextAutoConfiguration implements InitializingBean, ApplicationContextAware {
+
+ private ApplicationContext applicationContext;
+
+ @Bean
+ @ConditionalOnMissingBean(IUserContextHolder.class)
+ @ConditionalOnClass(name = "com.alibaba.ttl.TransmittableThreadLocal")
+ public IUserContextHolder userContextHolder() {
+ return new SimpleUserContextHolder();
+ }
+
+ @Override
+ public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
+ this.applicationContext = applicationContext;
+ }
+
+ @Override
+ public void afterPropertiesSet() throws Exception {
+ UserContextUtil.userContextHolder = applicationContext.getBean(IUserContextHolder.class);
+ }
+}
diff --git a/admin4j-common-spring-web/src/main/java/com/admin4j/common/config/UserContextConfig.java b/admin4j-common-spring-web/src/main/java/com/admin4j/common/config/UserContextConfig.java
deleted file mode 100644
index d22127a..0000000
--- a/admin4j-common-spring-web/src/main/java/com/admin4j/common/config/UserContextConfig.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package com.admin4j.common.config;
-
-import com.admin4j.common.service.IUserContextHolder;
-import com.admin4j.common.util.UserContextUtil;
-import org.springframework.beans.factory.InitializingBean;
-import org.springframework.beans.factory.annotation.Autowired;
-
-/**
- * @author andanyang
- * @since 2023/6/7 8:54
- */
-public class UserContextConfig implements InitializingBean {
-
-
- @Autowired(required = false)
- IUserContextHolder userContextHolder;
-
-
- @Override
- public void afterPropertiesSet() throws Exception {
-
- UserContextUtil.userContextHolder = userContextHolder;
- }
-}
diff --git a/web-spring-boot-starter/src/main/java/com/admin4j/framework/web/SimpleUserContextHolder.java b/admin4j-common-spring-web/src/main/java/com/admin4j/common/service/impl/SimpleUserContextHolder.java
similarity index 92%
rename from web-spring-boot-starter/src/main/java/com/admin4j/framework/web/SimpleUserContextHolder.java
rename to admin4j-common-spring-web/src/main/java/com/admin4j/common/service/impl/SimpleUserContextHolder.java
index 86e0b52..0d2aa3e 100644
--- a/web-spring-boot-starter/src/main/java/com/admin4j/framework/web/SimpleUserContextHolder.java
+++ b/admin4j-common-spring-web/src/main/java/com/admin4j/common/service/impl/SimpleUserContextHolder.java
@@ -1,4 +1,4 @@
-package com.admin4j.framework.web;
+package com.admin4j.common.service.impl;
import com.admin4j.common.pojo.AuthenticationUser;
import com.admin4j.common.pojo.ResponseEnum;
@@ -13,7 +13,6 @@
* @author andanyang
* @since 2021/7/27 10:56
*/
-
public class SimpleUserContextHolder implements IUserContextHolder {
/**
@@ -29,6 +28,11 @@ public void loginOut() {
clear();
}
+ @Override
+ public AuthenticationUser getAuthenticationUser() {
+ return THREAD_LOCAL_USER.get();
+ }
+
/**
* 设置登录者信息
*
@@ -39,11 +43,6 @@ public void setAuthenticationUser(AuthenticationUser authenticationUser) {
THREAD_LOCAL_USER.set(authenticationUser);
}
- @Override
- public AuthenticationUser getAuthenticationUser() {
- return THREAD_LOCAL_USER.get();
- }
-
/**
* 获取用户
*
@@ -90,6 +89,20 @@ public void offTenant() {
setTenantId(0L);
}
+ /**
+ * get租户
+ */
+ @Override
+ public Long getTenantId() {
+ AuthenticationUser loginUserNoCheck = getLoginUserNoCheck();
+ // 小心三目表达式,NPE
+ if (loginUserNoCheck == null) {
+ return null;
+ } else {
+ return loginUserNoCheck.getTenantId();
+ }
+ }
+
/**
* 设置租户
*
@@ -101,12 +114,11 @@ public void setTenantId(Long tenant) {
}
/**
- * get租户
+ * get用户ID
*/
@Override
- public Long getTenantId() {
- AuthenticationUser loginUserNoCheck = getLoginUserNoCheck();
- return loginUserNoCheck == null ? 0L : loginUserNoCheck.getTenantId();
+ public Long getUserId() {
+ return getLoginUser().getUserId();
}
/**
@@ -118,12 +130,4 @@ public Long getTenantId() {
public void setUserId(Long userId) {
getLoginUser().setUserId(userId);
}
-
- /**
- * get用户ID
- */
- @Override
- public Long getUserId() {
- return getLoginUser().getUserId();
- }
}
diff --git a/admin4j-common-spring-web/src/main/resources/META-INF/spring.factories b/admin4j-common-spring-web/src/main/resources/META-INF/spring.factories
index 15319b2..ad5cecb 100644
--- a/admin4j-common-spring-web/src/main/resources/META-INF/spring.factories
+++ b/admin4j-common-spring-web/src/main/resources/META-INF/spring.factories
@@ -1,2 +1,2 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
- com.admin4j.common.config.UserContextConfig
+ com.admin4j.common.config.UserContextAutoConfiguration
diff --git a/admin4j-dependencies/pom.xml b/admin4j-dependencies/pom.xml
index ed76042..3c2811c 100644
--- a/admin4j-dependencies/pom.xml
+++ b/admin4j-dependencies/pom.xml
@@ -215,7 +215,7 @@
com.admin4j.common
admin4j-common-spring-web
- ${admin4j.version}
+ 0.9.3-SNAPSHOT
com.admin4j.framework
diff --git a/pom.xml b/pom.xml
index ccd763d..304e251 100644
--- a/pom.xml
+++ b/pom.xml
@@ -43,8 +43,8 @@
enum-spring-boot-starter
- 0.9.0
- 0.9.2
+ 0.9.3-SNAPSHOT
+ 0.9.3-SNAPSHOT
8
8
UTF-8
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/context/SecurityUserContextHolder.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/context/SecurityUserContextHolder.java
index 54d313f..ec48f8f 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/context/SecurityUserContextHolder.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/context/SecurityUserContextHolder.java
@@ -1,10 +1,6 @@
package com.admin4j.framework.security.context;
-import com.admin4j.common.pojo.AuthenticationUser;
-import com.admin4j.common.pojo.ResponseEnum;
-import com.admin4j.common.service.IUserContextHolder;
-import com.alibaba.ttl.TransmittableThreadLocal;
-import org.apache.commons.lang3.ObjectUtils;
+import com.admin4j.common.service.impl.SimpleUserContextHolder;
/**
* 当前登录用户上下文信息,可实现切换用户,切换租户。
@@ -12,117 +8,6 @@
* @author andanyang
* @since 2021/7/27 10:56
*/
+public class SecurityUserContextHolder extends SimpleUserContextHolder {
-public class SecurityUserContextHolder implements IUserContextHolder {
-
- /**
- * 支持父子线程之间的数据传递 THREAD_LOCAL_TENANT
- */
- private final ThreadLocal THREAD_LOCAL_USER = new TransmittableThreadLocal<>();
-
- /**
- * 当前会话注销登录
- */
- @Override
- public void loginOut() {
- clear();
- }
-
- /**
- * 设置登录者信息
- *
- * @param authenticationUser 认证用户
- */
- @Override
- public void setAuthenticationUser(AuthenticationUser authenticationUser) {
- THREAD_LOCAL_USER.set(authenticationUser);
- }
-
- @Override
- public AuthenticationUser getAuthenticationUser() {
- return THREAD_LOCAL_USER.get();
- }
-
- /**
- * 获取用户
- *
- * @return String
- */
- public AuthenticationUser getLoginUser() {
- AuthenticationUser authenticationUser = THREAD_LOCAL_USER.get();
-
- ResponseEnum.FAIL_AUTH_FORBIDDEN.notNull(authenticationUser);
-
- return authenticationUser;
- }
-
- /**
- * 获取用户
- *
- * @return String
- */
- @Override
- public boolean isLogin() {
- AuthenticationUser authenticationUser = THREAD_LOCAL_USER.get();
- return ObjectUtils.isNotEmpty(authenticationUser);
- }
-
- /**
- * 获取用户
- *
- * @return String
- */
- public AuthenticationUser getLoginUserNoCheck() {
- return THREAD_LOCAL_USER.get();
- }
-
- /**
- * 清除LOCAL
- */
- @Override
- public void clear() {
- THREAD_LOCAL_USER.remove();
- }
-
- @Override
- public void offTenant() {
- setTenantId(0L);
- }
-
- /**
- * 设置租户
- *
- * @param tenant
- */
- @Override
- public void setTenantId(Long tenant) {
- getLoginUser().setTenantId(tenant);
- }
-
- /**
- * get租户
- */
- @Override
- public Long getTenantId() {
- AuthenticationUser loginUserNoCheck = getLoginUserNoCheck();
- return loginUserNoCheck == null ? 0L : loginUserNoCheck.getTenantId();
- }
-
- /**
- * 设置用户ID
- *
- * @param userId
- */
- @Override
- public void setUserId(Long userId) {
- getLoginUser().setUserId(userId);
- }
-
- /**
- * get用户ID
- */
- @Override
- public Long getUserId() {
- return getLoginUser().getUserId();
- }
}
diff --git a/web-spring-boot-starter/pom.xml b/web-spring-boot-starter/pom.xml
index 8cb145f..33f343e 100644
--- a/web-spring-boot-starter/pom.xml
+++ b/web-spring-boot-starter/pom.xml
@@ -15,11 +15,6 @@
0.9.3-SNAPSHOT
-
- com.alibaba
- transmittable-thread-local
- provided
-
com.admin4j.common
admin4j-common
diff --git a/web-spring-boot-starter/src/main/java/com/admin4j/framework/web/autoconfigure/UserContextAutoConfiguration.java b/web-spring-boot-starter/src/main/java/com/admin4j/framework/web/autoconfigure/UserContextAutoConfiguration.java
deleted file mode 100644
index a845c8a..0000000
--- a/web-spring-boot-starter/src/main/java/com/admin4j/framework/web/autoconfigure/UserContextAutoConfiguration.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package com.admin4j.framework.web.autoconfigure;
-
-import com.admin4j.common.constant.WebConstant;
-import com.admin4j.common.service.IUserContextHolder;
-import com.admin4j.framework.web.SimpleUserContextHolder;
-import org.springframework.boot.autoconfigure.AutoConfigureOrder;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-
-/**
- * @author andanyang
- * @since 2023/9/15 9:19
- */
-@Configuration
-@AutoConfigureOrder(WebConstant.IUserContextHolderOrder + 2)
-public class UserContextAutoConfiguration {
-
- @Bean
- @ConditionalOnMissingBean(IUserContextHolder.class)
- @ConditionalOnClass(name = "com.alibaba.ttl.TransmittableThreadLocal")
- public IUserContextHolder userContextHolder() {
- return new SimpleUserContextHolder();
- }
-}
diff --git a/web-spring-boot-starter/src/main/resources/META-INF/spring.factories b/web-spring-boot-starter/src/main/resources/META-INF/spring.factories
index b1da646..0619fd8 100644
--- a/web-spring-boot-starter/src/main/resources/META-INF/spring.factories
+++ b/web-spring-boot-starter/src/main/resources/META-INF/spring.factories
@@ -1,4 +1,3 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.admin4j.framework.web.autoconfigure.JacksonAutoConfiguration,\
- com.admin4j.framework.web.autoconfigure.WebAutoConfiguration,\
- com.admin4j.framework.web.autoconfigure.UserContextAutoConfiguration
\ No newline at end of file
+ com.admin4j.framework.web.autoconfigure.WebAutoConfiguration
\ No newline at end of file
From d15e6b98e74dc6966f627aff7313694f22af88ef Mon Sep 17 00:00:00 2001
From: andanyang <1218853253@qq.com>
Date: Tue, 19 Dec 2023 16:50:30 +0800
Subject: [PATCH 26/30] =?UTF-8?q?feat(security):=20PermissionAuthorization?=
=?UTF-8?q?Manager=20=E6=A0=A1=E9=AA=8C=20http=20=E6=96=B9=E6=B3=95?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../authorization/HttpUrlPermission.java | 29 ++++++++++++++
.../authorization/IPermissionUriService.java | 4 +-
.../PermissionAuthorizationManager.java | 38 ++++++++++++-------
3 files changed, 55 insertions(+), 16 deletions(-)
create mode 100644 security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/HttpUrlPermission.java
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/HttpUrlPermission.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/HttpUrlPermission.java
new file mode 100644
index 0000000..9e6bfd3
--- /dev/null
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/HttpUrlPermission.java
@@ -0,0 +1,29 @@
+package com.admin4j.framework.security.authorization;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.springframework.http.HttpMethod;
+
+/**
+ * http 请求权限数据
+ *
+ * @author andanyang
+ * @since 2023/12/19 16:08
+ */
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class HttpUrlPermission {
+
+ /**
+ * http 请求方法;
+ * 为null 表示不限制请求方法
+ */
+ private HttpMethod httpMethod;
+ /**
+ * http 请求地址
+ * 如: /user/1
+ */
+ private String requestURI;
+}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUriService.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUriService.java
index 8ce5e16..3cfdc96 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUriService.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUriService.java
@@ -15,12 +15,12 @@ public interface IPermissionUriService {
*
* @return
*/
- List allPermissionUri();
+ List allPermissionUrl();
/**
* 当前用户拥有的权限
*
* @return
*/
- List getMyPermissionUrls();
+ List getMyPermissionUrls();
}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java
index 944a94a..99a8ee3 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java
@@ -45,13 +45,14 @@ public AuthorizationDecision check(Supplier authentication, Requ
// 获取当前请求的 URL 地址
String requestURI = object.getRequest().getRequestURI();
- boolean matchPermission = matchPermission(requestURI);
+ String method = object.getRequest().getMethod();
+ boolean matchPermission = matchPermission(requestURI, method);
if (matchPermission) {
return GRANTED;
}
// 沒有匹配到, 查看当前 requestURI 是否需要权限控制
- return urlNeedPermission(requestURI) ? UN_AUTHORIZED : GRANTED;
+ return urlNeedPermission(requestURI, method) ? UN_AUTHORIZED : GRANTED;
}
/**
@@ -60,11 +61,15 @@ public AuthorizationDecision check(Supplier authentication, Requ
*
* @return
*/
- public boolean urlNeedPermission(String requestURI) {
-
- Collection allPermissionUrls = getAllPermissionUrls();
- for (String url : allPermissionUrls) {
- if (antPathMatcher.match(url, requestURI)) {
+ public boolean urlNeedPermission(String requestURI, String method) {
+
+ Collection allPermissionUrls = getAllPermissionUrls();
+ for (HttpUrlPermission urlPermission : allPermissionUrls) {
+ // method 相同 && 请求路径可以匹配
+ if (
+ (urlPermission.getHttpMethod() == null || urlPermission.getHttpMethod().name().equalsIgnoreCase(method))
+ &&
+ antPathMatcher.match(urlPermission.getRequestURI(), requestURI)) {
return true;
}
}
@@ -77,15 +82,20 @@ public boolean urlNeedPermission(String requestURI) {
* @param requestURI
* @return
*/
- public boolean matchPermission(String requestURI) {
- Collection permissionUrls = getPermissionUrls();
+ public boolean matchPermission(String requestURI, String method) {
+ Collection permissionUrls = getPermissionUrls();
if (permissionUrls == null || permissionUrls.isEmpty()) {
return false;
}
- for (String url : permissionUrls) {
- if (antPathMatcher.match(url, requestURI)) {
+ for (HttpUrlPermission urlPermission : permissionUrls) {
+
+ // method 相同 && 请求路径可以匹配
+ if (
+ (urlPermission.getHttpMethod() == null || urlPermission.getHttpMethod().name().equalsIgnoreCase(method))
+ &&
+ antPathMatcher.match(urlPermission.getRequestURI(), requestURI)) {
return true;
}
}
@@ -97,7 +107,7 @@ public boolean matchPermission(String requestURI) {
*
* @return
*/
- public Collection getPermissionUrls() {
+ public Collection getPermissionUrls() {
return permissionUriService.getMyPermissionUrls();
}
@@ -108,7 +118,7 @@ public Collection getPermissionUrls() {
*
* @return
*/
- protected Collection getAllPermissionUrls() {
- return permissionUriService.allPermissionUri();
+ protected Collection getAllPermissionUrls() {
+ return permissionUriService.allPermissionUrl();
}
}
From ce28c3db43080623b90275fec911765d9e98046f Mon Sep 17 00:00:00 2001
From: andanyang <1218853253@qq.com>
Date: Tue, 19 Dec 2023 17:15:17 +0800
Subject: [PATCH 27/30] =?UTF-8?q?feat(security):=20IPermissionUrlService?=
=?UTF-8?q?=20=E6=B7=BB=E5=8A=A0=20ignoreCheck=20=E6=96=B9=E6=B3=95?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
...iService.java => IPermissionUrlService.java} | 14 +++++++++++++-
.../PermissionAuthorizationManager.java | 17 ++++++++++++++++-
.../PermissionAutoConfiguration.java | 6 +++---
3 files changed, 32 insertions(+), 5 deletions(-)
rename security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/{IPermissionUriService.java => IPermissionUrlService.java} (61%)
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUriService.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUrlService.java
similarity index 61%
rename from security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUriService.java
rename to security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUrlService.java
index 3cfdc96..26e9863 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUriService.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUrlService.java
@@ -8,8 +8,18 @@
* @author andanyang
* @since 2023/12/19 14:34
*/
-public interface IPermissionUriService {
+public interface IPermissionUrlService {
+ /**
+ * 是否忽略 检查权限
+ * 例如 admin、管理员可以直接忽略检查拥有全部权限
+ *
+ * @return
+ */
+ default boolean ignoreCheck() {
+ return false;
+ }
+
/**
* 获取 系统 所有的 PermissionUri
*
@@ -23,4 +33,6 @@ public interface IPermissionUriService {
* @return
*/
List getMyPermissionUrls();
+
+
}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java
index 99a8ee3..543ac58 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java
@@ -29,7 +29,7 @@ public class PermissionAuthorizationManager implements AuthorizationManager authentication, RequestAuthorizationContext object) {
+ if (ignoreCheck()) {
+ return GRANTED;
+ }
+
// 获取当前请求的 URL 地址
String requestURI = object.getRequest().getRequestURI();
String method = object.getRequest().getMethod();
@@ -55,6 +59,17 @@ public AuthorizationDecision check(Supplier authentication, Requ
return urlNeedPermission(requestURI, method) ? UN_AUTHORIZED : GRANTED;
}
+ /**
+ * 是否忽略 检查权限
+ * 例如 admin、管理员可以直接忽略检查拥有全部权限
+ *
+ * @return
+ */
+ protected boolean ignoreCheck() {
+
+ return permissionUriService.ignoreCheck();
+ }
+
/**
* url 是否需要授权
* TODO 放在 service 立马
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/PermissionAutoConfiguration.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/PermissionAutoConfiguration.java
index b0f49f5..38445fa 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/PermissionAutoConfiguration.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/PermissionAutoConfiguration.java
@@ -1,6 +1,6 @@
package com.admin4j.framework.security.configuration;
-import com.admin4j.framework.security.authorization.IPermissionUriService;
+import com.admin4j.framework.security.authorization.IPermissionUrlService;
import com.admin4j.framework.security.authorization.PermissionAuthorizationManager;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
@@ -10,12 +10,12 @@
* @author andanyang
* @since 2023/12/19 14:40
*/
-@ConditionalOnBean(IPermissionUriService.class)
+@ConditionalOnBean(IPermissionUrlService.class)
@ConditionalOnMissingBean(PermissionAuthorizationManager.class)
public class PermissionAutoConfiguration {
@Bean
- public PermissionAuthorizationManager permissionAuthorizationManager(IPermissionUriService permissionUriService) {
+ public PermissionAuthorizationManager permissionAuthorizationManager(IPermissionUrlService permissionUriService) {
return new PermissionAuthorizationManager(permissionUriService);
}
From 049828dcf4721463e8993a2c7463c9b9cdd73d81 Mon Sep 17 00:00:00 2001
From: andanyang <1218853253@qq.com>
Date: Tue, 19 Dec 2023 17:26:50 +0800
Subject: [PATCH 28/30] =?UTF-8?q?feat(security):=20IPermissionUrlService?=
=?UTF-8?q?=20=E6=B7=BB=E5=8A=A0=20ignoreCheck=20=E6=96=B9=E6=B3=95?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../framework/security/properties/IgnoringUrlProperties.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/properties/IgnoringUrlProperties.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/properties/IgnoringUrlProperties.java
index c172df5..18fe56c 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/properties/IgnoringUrlProperties.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/properties/IgnoringUrlProperties.java
@@ -5,6 +5,7 @@
/**
* 根据配置文件 忽略url
+ * 注意支持 ant-style 风格语法;如果开头没有模糊匹配,请以 / 开头。
*
* @author andanyang
* @since 2023/3/24 17:00
@@ -15,6 +16,7 @@ public class IgnoringUrlProperties {
/**
* 包含所有请求类型的路径,不考虑请求方法
+ * 注意支持 ant-style 风格语法;如果开头没有模糊匹配,请以 / 开头。
*/
private String[] uris;
/**
@@ -37,6 +39,4 @@ public class IgnoringUrlProperties {
* patch 请求
*/
private String[] patch;
-
-
}
From e6023b6218403cbe52e66b9fb8b81e4b02be8cdd Mon Sep 17 00:00:00 2001
From: andanyang <1218853253@qq.com>
Date: Wed, 20 Dec 2023 11:54:33 +0800
Subject: [PATCH 29/30] =?UTF-8?q?feat(security):=20PermissionCode=20?=
=?UTF-8?q?=E4=BF=AE=E6=94=B9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../common/pojo/AuthenticationUser.java | 4 +-
.../com/admin4j/common/pojo/ResponseEnum.java | 2 +-
admin4j-dependencies/pom.xml | 4 +-
pom.xml | 2 +-
security-spring-boot-starter/README.md | 180 +++++++++++++++++-
.../authorization/IPermissionUrlService.java | 13 +-
.../PermissionAuthorizationManager.java | 20 ++
.../PermissionGrantedAuthority.java | 44 +++++
.../configuration/SecurityConfiguration.java | 6 +-
.../SecurityHandlerConfiguration.java | 3 +-
.../handler/SecurityExceptionHandler.java | 18 +-
.../security/jwt/JwtUserDetails.java | 39 ++--
.../security/jwt/TestJwtUserDetails.java | 12 --
.../autoconfigure/WebAutoConfiguration.java | 2 +-
14 files changed, 296 insertions(+), 53 deletions(-)
create mode 100644 security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionGrantedAuthority.java
diff --git a/admin4j-common-spring-web/src/main/java/com/admin4j/common/pojo/AuthenticationUser.java b/admin4j-common-spring-web/src/main/java/com/admin4j/common/pojo/AuthenticationUser.java
index a6e6f83..68cd82e 100644
--- a/admin4j-common-spring-web/src/main/java/com/admin4j/common/pojo/AuthenticationUser.java
+++ b/admin4j-common-spring-web/src/main/java/com/admin4j/common/pojo/AuthenticationUser.java
@@ -5,7 +5,7 @@
import lombok.Data;
import java.io.Serializable;
-import java.util.Set;
+import java.util.Collection;
/**
* UserContext 用户上下文
@@ -35,7 +35,7 @@ public class AuthenticationUser implements Serializable {
* 权限列表
*/
@ApiModelProperty("权限code列表")
- private Set permissions;
+ private Collection permissions;
// private String fromService;
diff --git a/admin4j-common/src/main/java/com/admin4j/common/pojo/ResponseEnum.java b/admin4j-common/src/main/java/com/admin4j/common/pojo/ResponseEnum.java
index e56820b..3e921c1 100644
--- a/admin4j-common/src/main/java/com/admin4j/common/pojo/ResponseEnum.java
+++ b/admin4j-common/src/main/java/com/admin4j/common/pojo/ResponseEnum.java
@@ -33,7 +33,7 @@ public enum ResponseEnum implements IResponse, Assert {
*/
FAIL_AUTH(402, "登录失败,账号或者密码错误"),
/**
- *
+ * 没有权限
*/
FAIL_AUTH_FORBIDDEN(403, "FAIL_AUTH_FORBIDDEN"),
diff --git a/admin4j-dependencies/pom.xml b/admin4j-dependencies/pom.xml
index 3c2811c..9901d44 100644
--- a/admin4j-dependencies/pom.xml
+++ b/admin4j-dependencies/pom.xml
@@ -6,7 +6,7 @@
com.admin4j
admin4j-dependencies
- 0.9.3-SNAPSHOT
+ 0.9.5-SNAPSHOT
pom
${project.artifactId}
@@ -64,7 +64,7 @@
6.7.2
0.1.2
- 0.9.0
+ 0.9.5-SNAPSHOT
0.8.2
0.8.0
0.8.0
diff --git a/pom.xml b/pom.xml
index 304e251..103530f 100644
--- a/pom.xml
+++ b/pom.xml
@@ -43,7 +43,7 @@
enum-spring-boot-starter
- 0.9.3-SNAPSHOT
+ 0.9.5-SNAPSHOT
0.9.3-SNAPSHOT
8
8
diff --git a/security-spring-boot-starter/README.md b/security-spring-boot-starter/README.md
index 90a0a4a..2ac34f2 100644
--- a/security-spring-boot-starter/README.md
+++ b/security-spring-boot-starter/README.md
@@ -1,14 +1,19 @@
# admin security
-## Features
+Spring Security 最佳实践封装。
+
+# Features
- 多渠道登录
-- 一个注解/一个配置,解决匿名url访问(忽略认证)
+- 匿名url访问:一个注解/一个配置,解决匿名url访问(忽略认证)
+- 注解式权限
- 基于数据库的动态权限
-## USAGES
+# USAGES
+
+## 1. 基础使用
-1. 引入 pom
+### 1.1 引入 pom
```
@@ -18,7 +23,7 @@
```
-2. 实现 JwtUserDetailsService 接口,用于根据用户ID获取用户详情。由于我们的JWT Token 存的是 userId,所以这里的入参为userId
+### 1.2 实现 JwtUserDetailsService 接口,用于根据用户ID获取用户详情。由于我们的JWT Token 存的是 userId,所以这里的入参为userId
```java
@@ -36,7 +41,7 @@ public class Admin4jJwtUserDetailsService implements JwtUserDetailsService {
}
```
-3. 账号密码登录。需要实现 `Spring Security`的`UserDetailsService` 接口,用于根据 username 查询用户详情
+### 1.3 账号密码登录。需要实现 `Spring Security`的`UserDetailsService` 接口,用于根据 username 查询用户详情
```java
@@ -63,7 +68,7 @@ public class Admin4jJwtUserDetailsService implements JwtUserDetailsService, User
```
-### 测试
+### 1.4 测试
- 登录接口
@@ -86,11 +91,166 @@ curl --location 'http://localhost:8080/login' \
}
```
-## 多渠道登录
+## 2. 匿名url访问
+
+### 2.1 注解式
+
+> `@AnonymousAccess`需要放在 `controller`方法上
+
+```
+public class UserProfileController {
+
+ @GetMapping("1")
+ @ApiModelProperty("注解式匿名url访问")
+ @AnonymousAccess
+ public R get() {
+ return R.ok("1");
+ }
+```
+
+### 2.2 yml配置式
+
+> 支持HttpMethod(get,post,put,delete)配置;uris下面表示所有HttpMethod
+
+```
+admin4j:
+ security:
+ ignoring:
+ uris:
+ - "/login/sendPhoneCode"
+ - "/profile/**"
+ get:
+ - "/profile/3"
+```
+
+## 3. 注解式权限
+
+### 3.1 开启方法注解式权限
+
+```
+@EnableGlobalMethodSecurity(prePostEnabled = true)
+public class AdminServerApplication {
+}
+```
+
+### 3.2 使用
+
+```
+ @GetMapping("4")
+ @PreAuthorize("hasAuthority('profile')")
+ public R get4() {
+ return R.ok("4");
+ }
+
+ @GetMapping("5")
+ @PreAuthorize("hasAuthority('menus')")
+ public R get5() {
+ return R.ok("5");
+ }
+```
+
+### 3.3 `@PreAuthorize` 支持el表达式
+
+#### 3.3.1. returnObject 保留名
+
+对于 @PostAuthorize 和 @PostFilter 注解, 可以在表达式中使用 returnObject 保留名, returnObject 代表着被注解方法的返回值,
+我们可以使用 returnObject 保留名对注解方法的结果进行验证.
+比如:
+
+```java
+
+@PostAuthorize("returnObject.owner == authentication.name")
+public Book getBook();
+12
+```
+
+#### 3.3.2. 表达式中的 # 号
+
+在表达式中, 可以使用 #argument123 的形式来代表注解方法中的参数 argument123.
+比如:
+
+```java
+
+@PreAuthorize("#book.owner == authentication.name")
+public void deleteBook(Book book);
+12
+```
+
+还有一种 #argument123 的写法, 即使用 Spring Security @P注解来为方法参数起别名, 然后在 @PreAuthorize 等注解表达式中使用该别名.
+不推荐这种写法, 代码可读性较差.
+
+```java
+
+@PreAuthorize("#c.name == authentication.name")
+public void doSomething(@P("c") Contact contact);
+```
+
+#### 3.3.3 内置表达式有:
+
+| 表达式 | 备注 |
+|--------------------------------------------------------------------|----------------------------------------|
+| hasRole([role]) | 如果有当前角色, 则返回 true(会自动加上 ROLE_ 前缀) |
+| hasAnyRole([role1, role2]) | 如果有任一角色即可通过校验, 返回true,(会自动加上 ROLE_ 前缀) |
+| hasAuthority([authority]) | 如果有指定权限, 则返回 true |
+| hasAnyAuthority([authority1, authority2]) | 如果有任一指定权限, 则返回true |
+| principal | 获取当前用户的 principal 主体对象 |
+| authentication | 获取当前用户的 authentication 对象, |
+| permitAll | 总是返回 true, 表示全部允许 |
+| denyAll | 总是返回 false, 代表全部拒绝 |
+| isAnonymous() | 如果是匿名访问, 返回true |
+| isRememberMe() | 如果是remember-me 自动认证, 则返回 true |
+| isAuthenticated() | 如果不是匿名访问, 则返回true |
+| isFullAuthenticated() | 如果不是匿名访问或remember-me认证登陆, 则返回true |
+| hasPermission(Object target, Object permission) | |
+| hasPermission(Object target, String targetType, Object permission) | |
+
+## 4. 基于数据库的动态权限
+
+实现 接口`IPermissionUrlService`
+
+```
+public interface IPermissionUrlService {
+
+ /**
+ * 是否忽略 检查权限
+ * 例如 admin、管理员可以直接忽略检查拥有全部权限
+ *
+ * @return
+ */
+ default boolean ignoreCheck() {
+ return false;
+ }
+
+ /**
+ * 是否允许匿名访问
+ *
+ * @return
+ */
+ default boolean canAnonymousAccess() {
+ return false;
+ }
+
+ /**
+ * 获取系统所有需要授权的 PermissionUri
+ *
+ * @return
+ */
+ List allPermissionUrl();
+
+ /**
+ * 当前用户拥有的权限
+ *
+ * @return
+ */
+ List getMyPermissionUrls();
+}
+```
+
+## 5.多渠道登录
通过配置的方式,支持微信,手机号等多渠道登录
-### 验证码手机号登录
+### 5.1 验证码手机号登录
- yaml配置方式
@@ -127,7 +287,6 @@ curl --location 'http://localhost:8080/login/phone' \
3. 根据手机号获取用户详情
```java
-
/**
* 验证码手机号登录
*
@@ -162,3 +321,4 @@ public class PhoneMultiUserDetailsService implements MultiUserDetailsService {
```
### 其他渠道登录,如微信openid 登录,参考上方可实现
+
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUrlService.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUrlService.java
index 26e9863..fa1458b 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUrlService.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/IPermissionUrlService.java
@@ -19,9 +19,18 @@ public interface IPermissionUrlService {
default boolean ignoreCheck() {
return false;
}
-
+
+ /**
+ * 是否允许匿名访问
+ *
+ * @return
+ */
+ default boolean canAnonymousAccess() {
+ return false;
+ }
+
/**
- * 获取 系统 所有的 PermissionUri
+ * 获取系统所有需要授权的 PermissionUri
*
* @return
*/
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java
index 543ac58..32af2ce 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionAuthorizationManager.java
@@ -1,6 +1,7 @@
package com.admin4j.framework.security.authorization;
import lombok.RequiredArgsConstructor;
+import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
@@ -43,6 +44,15 @@ public class PermissionAuthorizationManager implements AuthorizationManager authentication, RequestAuthorizationContext object) {
+ // 是否允许匿名访问
+ if (!canAnonymousAccess()) {
+ Authentication authenticationGet = authentication.get();
+ if (authenticationGet instanceof AnonymousAuthenticationToken) {
+ // 匿名访问
+ return UN_AUTHORIZED;
+ }
+ }
+
if (ignoreCheck()) {
return GRANTED;
}
@@ -59,6 +69,16 @@ public AuthorizationDecision check(Supplier authentication, Requ
return urlNeedPermission(requestURI, method) ? UN_AUTHORIZED : GRANTED;
}
+ /**
+ * 是否允许匿名访问。
+ * 默认不允许。
+ *
+ * @return
+ */
+ protected boolean canAnonymousAccess() {
+ return permissionUriService.canAnonymousAccess();
+ }
+
/**
* 是否忽略 检查权限
* 例如 admin、管理员可以直接忽略检查拥有全部权限
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionGrantedAuthority.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionGrantedAuthority.java
new file mode 100644
index 0000000..af25bd1
--- /dev/null
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/authorization/PermissionGrantedAuthority.java
@@ -0,0 +1,44 @@
+package com.admin4j.framework.security.authorization;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.springframework.security.access.AccessDecisionManager;
+import org.springframework.security.core.GrantedAuthority;
+
+/**
+ * 权限字符串code
+ *
+ * @author andanyang
+ * @since 2023/12/20 10:29
+ */
+@AllArgsConstructor
+@NoArgsConstructor
+@Data
+public class PermissionGrantedAuthority implements GrantedAuthority {
+
+ private static final long serialVersionUID = -2619854289135953331L;
+ // 权限字符串code
+ private String permission;
+
+ /**
+ * If the GrantedAuthority
can be represented as a String
+ * and that String
is sufficient in precision to be relied upon for an
+ * access control decision by an {@link AccessDecisionManager} (or delegate), this
+ * method should return such a String
.
+ *
+ * If the GrantedAuthority
cannot be expressed with sufficient precision
+ * as a String
, null
should be returned. Returning
+ * null
will require an AccessDecisionManager
(or delegate)
+ * to specifically support the GrantedAuthority
implementation, so
+ * returning null
should be avoided unless actually required.
+ *
+ * @return a representation of the granted authority (or null
if the
+ * granted authority cannot be expressed as a String
with sufficient
+ * precision).
+ */
+ @Override
+ public String getAuthority() {
+ return permission;
+ }
+}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityConfiguration.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityConfiguration.java
index d9bb4b5..642ae8c 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityConfiguration.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityConfiguration.java
@@ -16,7 +16,6 @@
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
-import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer;
@@ -43,11 +42,12 @@
*/
/**
- * 开启方法级别的注解支持
+ * spring security 配置。
*
* @author andanyang
+ * @EnableGlobalMethodSecurity 有应用出自己开启
*/
-@EnableGlobalMethodSecurity(prePostEnabled = true)
+// @EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableConfigurationProperties({IgnoringUrlProperties.class, JwtProperties.class, FormLoginProperties.class, MultiAuthenticationProperties.class})
@AutoConfigureBefore(UserDetailsServiceAutoConfiguration.class)
public class SecurityConfiguration {
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityHandlerConfiguration.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityHandlerConfiguration.java
index 8734f9c..e34b926 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityHandlerConfiguration.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/configuration/SecurityHandlerConfiguration.java
@@ -3,7 +3,6 @@
import com.admin4j.framework.security.AuthenticationHandler;
import com.admin4j.framework.security.UserTokenService;
import com.admin4j.framework.security.handler.*;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.web.AuthenticationEntryPoint;
@@ -51,7 +50,7 @@ public LogoutSuccessHandler logoutSuccessHandler(AuthenticationHandler authentic
}
@Bean
- @ConditionalOnClass(name = {"io.jsonwebtoken.SignatureException"})
+ // @ConditionalOnClass(name = {"io.jsonwebtoken.SignatureException"})
public SecurityExceptionHandler securityExceptionHandler() {
return new SecurityExceptionHandler();
}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/SecurityExceptionHandler.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/SecurityExceptionHandler.java
index 73220d9..5a8aa7c 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/SecurityExceptionHandler.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/handler/SecurityExceptionHandler.java
@@ -1,8 +1,14 @@
package com.admin4j.framework.security.handler;
import com.admin4j.common.exception.handler.AbstractExceptionHandler;
+import com.admin4j.common.pojo.IResponse;
+import com.admin4j.common.pojo.ResponseEnum;
+import com.admin4j.common.pojo.SimpleResponse;
import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
/**
* @author andanyang
@@ -12,11 +18,11 @@
@ControllerAdvice
public class SecurityExceptionHandler extends AbstractExceptionHandler {
-// @ExceptionHandler(SignatureException.class)
-// @Deprecated
-// public ResponseEntity handleException(Exception e) {
-// log.error("SignatureException:" + e.getMessage(), e);
-// return renderException(e, SimpleResponse.of(ResponseEnum.FAIL_AUTH_TOKEN_ERROR.getCode(), e.getMessage()));
-// }
+ @ExceptionHandler(AccessDeniedException.class)
+ @Deprecated
+ public ResponseEntity handleException(Exception e) {
+ log.error("AccessDeniedException:" + e.getMessage(), e);
+ return renderException(e, SimpleResponse.of(ResponseEnum.FAIL_AUTH_FORBIDDEN.getCode(), e.getMessage()));
+ }
}
diff --git a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/jwt/JwtUserDetails.java b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/jwt/JwtUserDetails.java
index 9006ed4..9a73a8d 100644
--- a/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/jwt/JwtUserDetails.java
+++ b/security-spring-boot-starter/src/main/java/com/admin4j/framework/security/jwt/JwtUserDetails.java
@@ -1,8 +1,15 @@
package com.admin4j.framework.security.jwt;
+import com.admin4j.framework.security.authorization.PermissionGrantedAuthority;
+import com.alibaba.fastjson2.annotation.JSONField;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import org.apache.commons.lang3.ObjectUtils;
+import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
-import java.util.Set;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.stream.Collectors;
/**
* @author andanyang
@@ -11,14 +18,14 @@
public interface JwtUserDetails extends UserDetails {
- //private static final long serialVersionUID = -5943535608623539244L;
- //private String password;
- //private String username;
- //private Set authorities;
- //private boolean accountNonExpired = true;
- //private boolean accountNonLocked = true;
- //private boolean credentialsNonExpired = true;
- //private boolean enabled = true;
+ // private static final long serialVersionUID = -5943535608623539244L;
+ // private String password;
+ // private String username;
+ // private Set authorities;
+ // private boolean accountNonExpired = true;
+ // private boolean accountNonLocked = true;
+ // private boolean credentialsNonExpired = true;
+ // private boolean enabled = true;
/**
* jwt 盐
@@ -44,11 +51,21 @@ default Long getTenantId() {
/**
* 登录方式
*/
- String getAuthType();
+ default String getAuthType() {
+ return "";
+ }
/**
* 权限列表
*/
- Set getPermissions();
+ Collection getPermissions();
+ @JsonIgnore
+ @JSONField(serialize = false)
+ default Collection getAuthorities() {
+ if (ObjectUtils.isEmpty(getPermissions())) {
+ return Collections.emptySet();
+ }
+ return getPermissions().stream().map(PermissionGrantedAuthority::new).collect(Collectors.toSet());
+ }
}
diff --git a/security-spring-boot-starter/src/test/java/com/admin4j/framework/security/jwt/TestJwtUserDetails.java b/security-spring-boot-starter/src/test/java/com/admin4j/framework/security/jwt/TestJwtUserDetails.java
index 9210063..8974a27 100644
--- a/security-spring-boot-starter/src/test/java/com/admin4j/framework/security/jwt/TestJwtUserDetails.java
+++ b/security-spring-boot-starter/src/test/java/com/admin4j/framework/security/jwt/TestJwtUserDetails.java
@@ -1,9 +1,7 @@
package com.admin4j.framework.security.jwt;
import lombok.Data;
-import org.springframework.security.core.GrantedAuthority;
-import java.util.Collection;
import java.util.Set;
/**
@@ -33,16 +31,6 @@ public Set getPermissions() {
}
- /**
- * Returns the authorities granted to the user. Cannot return null
.
- *
- * @return the authorities, sorted by natural key (never null
)
- */
- @Override
- public Collection extends GrantedAuthority> getAuthorities() {
- return null;
- }
-
/**
* Returns the password used to authenticate the user.
*
diff --git a/web-spring-boot-starter/src/main/java/com/admin4j/framework/web/autoconfigure/WebAutoConfiguration.java b/web-spring-boot-starter/src/main/java/com/admin4j/framework/web/autoconfigure/WebAutoConfiguration.java
index 1c3e74a..908aa35 100644
--- a/web-spring-boot-starter/src/main/java/com/admin4j/framework/web/autoconfigure/WebAutoConfiguration.java
+++ b/web-spring-boot-starter/src/main/java/com/admin4j/framework/web/autoconfigure/WebAutoConfiguration.java
@@ -46,7 +46,7 @@ public Admin4jErrorController basicErrorController(ErrorAttributes errorAttribut
*
* @return
*/
- @Bean
+ @Bean("admin4jGlobalExceptionHandler")
public GlobalExceptionHandler globalExceptionHandler() {
return new GlobalExceptionHandler();
}
From 98a83a23e404cf977d1acb30d2b5018480fc6e2d Mon Sep 17 00:00:00 2001
From: andanyang <1218853253@qq.com>
Date: Wed, 20 Dec 2023 14:23:46 +0800
Subject: [PATCH 30/30] feat(version): update version 0.9.5
---
admin4j-common-spring-web/pom.xml | 2 +-
admin4j-dependencies/pom.xml | 32 +++++++++++++-------------
admin4j-parent/pom.xml | 4 ++--
excel-spring-boot-starter/pom.xml | 4 ++--
mybatis-plus-boot-starter/pom.xml | 2 +-
pom.xml | 4 ++--
prometheus-spring-boot-starter/pom.xml | 3 ++-
security-spring-boot-starter/README.md | 13 ++++++-----
security-spring-boot-starter/pom.xml | 2 +-
tenant-spring-boot-starter/pom.xml | 2 +-
test-spring-boot-starter/pom.xml | 2 +-
ttl-spring-boot-starter/pom.xml | 1 +
web-spring-boot-starter/pom.xml | 2 +-
13 files changed, 38 insertions(+), 35 deletions(-)
diff --git a/admin4j-common-spring-web/pom.xml b/admin4j-common-spring-web/pom.xml
index bbf0a85..d9f85c7 100644
--- a/admin4j-common-spring-web/pom.xml
+++ b/admin4j-common-spring-web/pom.xml
@@ -11,7 +11,7 @@
com.admin4j.common
admin4j-common-spring-web
- 0.9.3-SNAPSHOT
+ 0.9.5
与业务无关的工具类库
diff --git a/admin4j-dependencies/pom.xml b/admin4j-dependencies/pom.xml
index 9901d44..83fcdea 100644
--- a/admin4j-dependencies/pom.xml
+++ b/admin4j-dependencies/pom.xml
@@ -6,7 +6,7 @@
com.admin4j
admin4j-dependencies
- 0.9.5-SNAPSHOT
+ 0.9.5
pom
${project.artifactId}
@@ -64,7 +64,7 @@
6.7.2
0.1.2
- 0.9.5-SNAPSHOT
+ 0.9.5
0.8.2
0.8.0
0.8.0
@@ -125,42 +125,42 @@
com.admin4j.framework
tenant-spring-boot-starter
- 0.9.3-SNAPSHOT
+ 0.9.5
com.admin4j.framework
ttl-spring-boot-starter
- ${admin4j.version}
+ 0.9.0
com.admin4j.framework
excel-spring-boot-starter
- ${admin4j.version}
+ 0.9.0
com.admin4j.framework
log-spring-boot-starter
- ${admin4j.version}
+ 0.9.0
com.admin4j.framework
test-spring-boot-starter
- ${admin4j.version}
+ 0.9.0
com.admin4j.framework
desensitize-spring-boot-starter
- ${admin4j.version}
+ 0.9.0
com.admin4j.framework
security-spring-boot-starter
- 0.9.4-SNAPSHOT
+ 0.9.5
com.admin4j.framework
mybatis-plus-boot-starter
- 0.9.3-SNAPSHOT
+ 0.9.5
com.admin4j.framework
@@ -215,12 +215,12 @@
com.admin4j.common
admin4j-common-spring-web
- 0.9.3-SNAPSHOT
+ 0.9.5
com.admin4j.framework
web-spring-boot-starter
- 0.9.3-SNAPSHOT
+ 0.9.5
com.admin4j.framework
@@ -230,12 +230,12 @@
com.admin4j.framework
prometheus-spring-boot-starter
- ${admin4j.version}
+ 0.9.5
com.admin4j.framework
excel-spring-boot-starter
- ${admin4j.version}
+ 0.9.0
com.admin4j
@@ -356,7 +356,7 @@
com.alibaba.fastjson2
fastjson2
- 2.0.29
+ 2.0.43
@@ -375,7 +375,7 @@
com.github.pagehelper
pagehelper-spring-boot-starter
- 2.0.0
+ 2.1.0
diff --git a/admin4j-parent/pom.xml b/admin4j-parent/pom.xml
index ff170c8..55f1299 100644
--- a/admin4j-parent/pom.xml
+++ b/admin4j-parent/pom.xml
@@ -6,13 +6,13 @@
com.admin4j
admin4j-parent
- 0.9.2
+ 0.9.5
用于业务框架的父工程
pom
admin4j-parent
https://github.com/admin4j/admin4j-framework
- 0.9.2
+ 0.9.5
8
8
UTF-8
diff --git a/excel-spring-boot-starter/pom.xml b/excel-spring-boot-starter/pom.xml
index 08a4068..1f8f549 100644
--- a/excel-spring-boot-starter/pom.xml
+++ b/excel-spring-boot-starter/pom.xml
@@ -1,4 +1,4 @@
-
4.0.0
@@ -9,7 +9,7 @@
com.admin4j.framework
excel-spring-boot-starter
-
+ 0.9.0
jar
excel-spring-boot-starter
diff --git a/mybatis-plus-boot-starter/pom.xml b/mybatis-plus-boot-starter/pom.xml
index 0b86dfd..f580ead 100644
--- a/mybatis-plus-boot-starter/pom.xml
+++ b/mybatis-plus-boot-starter/pom.xml
@@ -12,7 +12,7 @@
jar
mybatis-plus-boot-starter
- 0.9.3-SNAPSHOT
+ 0.9.5
diff --git a/pom.xml b/pom.xml
index 103530f..8e1fec0 100644
--- a/pom.xml
+++ b/pom.xml
@@ -43,8 +43,8 @@
enum-spring-boot-starter
- 0.9.5-SNAPSHOT
- 0.9.3-SNAPSHOT
+ 0.9.5
+ 0.9.5
8
8
UTF-8
diff --git a/prometheus-spring-boot-starter/pom.xml b/prometheus-spring-boot-starter/pom.xml
index e1298fe..2135903 100644
--- a/prometheus-spring-boot-starter/pom.xml
+++ b/prometheus-spring-boot-starter/pom.xml
@@ -1,4 +1,4 @@
-
4.0.0
@@ -9,6 +9,7 @@
com.admin4j.framework
prometheus-spring-boot-starter
+ 0.9.5
jar
prometheus-spring-boot-starter
diff --git a/security-spring-boot-starter/README.md b/security-spring-boot-starter/README.md
index 2ac34f2..6b7c10d 100644
--- a/security-spring-boot-starter/README.md
+++ b/security-spring-boot-starter/README.md
@@ -15,12 +15,13 @@ Spring Security 最佳实践封装。
### 1.1 引入 pom
-```
-
- com.admin4j.framework
- security-spring-boot-starter
- 0.9.0
-
+```xml
+
+
+ com.admin4j.framework
+ security-spring-boot-starter
+ 0.9.0
+
```
### 1.2 实现 JwtUserDetailsService 接口,用于根据用户ID获取用户详情。由于我们的JWT Token 存的是 userId,所以这里的入参为userId
diff --git a/security-spring-boot-starter/pom.xml b/security-spring-boot-starter/pom.xml
index 142144f..a5429cf 100644
--- a/security-spring-boot-starter/pom.xml
+++ b/security-spring-boot-starter/pom.xml
@@ -10,7 +10,7 @@
com.admin4j.framework
security-spring-boot-starter
jar
- 0.9.5-SNAPSHOT
+ 0.9.5
security-spring-boot-starter
diff --git a/tenant-spring-boot-starter/pom.xml b/tenant-spring-boot-starter/pom.xml
index 114a7d0..d073cf5 100644
--- a/tenant-spring-boot-starter/pom.xml
+++ b/tenant-spring-boot-starter/pom.xml
@@ -9,7 +9,7 @@
com.admin4j.framework
tenant-spring-boot-starter
- 0.9.3-SNAPSHOT
+ 0.9.5
tenant-spring-boot-starter
多各大中间件的,多租户能力的适配
diff --git a/test-spring-boot-starter/pom.xml b/test-spring-boot-starter/pom.xml
index 2616af7..5e68001 100644
--- a/test-spring-boot-starter/pom.xml
+++ b/test-spring-boot-starter/pom.xml
@@ -1,4 +1,4 @@
-
4.0.0
diff --git a/ttl-spring-boot-starter/pom.xml b/ttl-spring-boot-starter/pom.xml
index 3d5bb33..7e70ae0 100644
--- a/ttl-spring-boot-starter/pom.xml
+++ b/ttl-spring-boot-starter/pom.xml
@@ -9,6 +9,7 @@
com.admin4j.framework
ttl-spring-boot-starter
+ 0.9.0
jar
ttl-spring-boot-starter
diff --git a/web-spring-boot-starter/pom.xml b/web-spring-boot-starter/pom.xml
index 33f343e..258faa0 100644
--- a/web-spring-boot-starter/pom.xml
+++ b/web-spring-boot-starter/pom.xml
@@ -12,7 +12,7 @@
com.admin4j.framework
web-spring-boot-starter
${project.artifactId}
- 0.9.3-SNAPSHOT
+ 0.9.5