完善TokenIgnore,支持Controller

This commit is contained in:
COOL
2024-07-24 17:01:02 +08:00
parent 12ac71e93f
commit ba400993dc
5 changed files with 119 additions and 89 deletions

View File

@@ -11,4 +11,5 @@ import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD}) @Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface TokenIgnore { public @interface TokenIgnore {
String[] value() default {};
} }

View File

@@ -1,6 +1,5 @@
package com.cool.core.security; package com.cool.core.security;
import com.cool.core.annotation.CoolRestController;
import com.cool.core.annotation.TokenIgnore; import com.cool.core.annotation.TokenIgnore;
import com.cool.modules.base.security.JwtAuthenticationTokenFilter; import com.cool.modules.base.security.JwtAuthenticationTokenFilter;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -22,7 +21,6 @@ import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.DigestUtils; import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.web.method.HandlerMethod; import org.springframework.web.method.HandlerMethod;
@@ -31,8 +29,9 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandl
import org.springframework.web.util.pattern.PathPattern; import org.springframework.web.util.pattern.PathPattern;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.Predicate;
@EnableWebSecurity @EnableWebSecurity
@Configuration @Configuration
@@ -59,9 +58,12 @@ public class JwtSecurityConfig {
return httpSecurity return httpSecurity
.authorizeHttpRequests( .authorizeHttpRequests(
conf -> conf.requestMatchers( conf -> {
conf.requestMatchers(
ignoredUrlsProperties.getUrls().toArray(String[]::new)) ignoredUrlsProperties.getUrls().toArray(String[]::new))
.permitAll().anyRequest().authenticated()) .permitAll();
conf.requestMatchers("/admin/**").authenticated();
})
.headers(config -> config.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)) .headers(config -> config.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
// 允许网页iframe // 允许网页iframe
.csrf(AbstractHttpConfigurer::disable) .csrf(AbstractHttpConfigurer::disable)
@@ -76,9 +78,26 @@ public class JwtSecurityConfig {
private void configureIgnoredUrls() { private void configureIgnoredUrls() {
Map<RequestMappingInfo, HandlerMethod> mappings = requestMappingHandlerMapping.getHandlerMethods(); Map<RequestMappingInfo, HandlerMethod> mappings = requestMappingHandlerMapping.getHandlerMethods();
List<String> handlerCtr = new ArrayList<>();
mappings.forEach((requestMappingInfo, handlerMethod) -> { mappings.forEach((requestMappingInfo, handlerMethod) -> {
Method method = handlerMethod.getMethod(); Method method = handlerMethod.getMethod();
TokenIgnore tokenIgnore = AnnotatedElementUtils.findMergedAnnotation(method, TokenIgnore.class); TokenIgnore tokenIgnore = AnnotatedElementUtils.findMergedAnnotation(method, TokenIgnore.class);
TokenIgnore tokenIgnoreCtr = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getBeanType(), TokenIgnore.class);
if (!handlerCtr.contains(handlerMethod.getBeanType().getName()) && tokenIgnoreCtr != null) {
requestMappingInfo.getPathPatternsCondition().getPatterns().forEach(pathPattern -> {
String[] prefixs = pathPattern.getPatternString().split("/");
// 去除最后一个路径
List<String> urls = new ArrayList<>();
for (int i = 0; i < prefixs.length - 1; i++) {
urls.add(prefixs[i]);
}
// 遍历 tokenIgnoreCtr.value()
for (String path : tokenIgnoreCtr.value()) {
ignoredUrlsProperties.getUrls().add(String.join("/", urls) + "/" + path);
}
handlerCtr.add(handlerMethod.getBeanType().getName());
});
}
if (tokenIgnore != null) { if (tokenIgnore != null) {
StringBuilder url = new StringBuilder(); StringBuilder url = new StringBuilder();
RequestMapping classRequestMapping = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getBeanType(), RequestMapping.class); RequestMapping classRequestMapping = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getBeanType(), RequestMapping.class);
@@ -90,7 +109,6 @@ public class JwtSecurityConfig {
if (requestMappingInfo.getPathPatternsCondition() == null) { if (requestMappingInfo.getPathPatternsCondition() == null) {
return; return;
} }
// requestMappingInfo.getPathPatternsCondition().getPatterns()
for (PathPattern path : requestMappingInfo.getPathPatternsCondition().getPatterns()) { for (PathPattern path : requestMappingInfo.getPathPatternsCondition().getPatterns()) {
url.append(path); url.append(path);
} }

View File

@@ -1,5 +1,6 @@
package com.cool.core.security; package com.cool.core.security;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.AccessDeniedException;
@@ -7,23 +8,34 @@ import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
/** /**
* 权限管理决断器 判断用户拥有的权限或角色是否有资源访问权限 * 权限管理决断器 判断用户拥有的权限或角色是否有资源访问权限
*/ */
@RequiredArgsConstructor
@Slf4j @Slf4j
@Component @Component
public class MyAccessDecisionManager implements AccessDecisionManager { public class MyAccessDecisionManager implements AccessDecisionManager {
// 忽略权限控制的地址
final private IgnoredUrlsProperties ignoredUrlsProperties;
@Override @Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> configAttributes) public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> configAttributes)
throws AccessDeniedException, InsufficientAuthenticationException { throws AccessDeniedException, InsufficientAuthenticationException {
if (configAttributes == null) { if (configAttributes == null) {
return; return;
} }
List<String> urls = ignoredUrlsProperties.getUrls();
String url = ((FilterInvocation) o).getRequestUrl().split("[?]")[0];
if (urls.contains(url)) {
return;
}
Iterator<ConfigAttribute> iterator = configAttributes.iterator(); Iterator<ConfigAttribute> iterator = configAttributes.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
ConfigAttribute c = iterator.next(); ConfigAttribute c = iterator.next();

View File

@@ -11,16 +11,15 @@ import com.cool.modules.dict.service.DictInfoService;
import com.mybatisflex.core.query.QueryWrapper; import com.mybatisflex.core.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import jakarta.servlet.http.HttpServletRequest;
/** /**
* 字典信息 * 字典信息
*/ */
@Tag(name = "字典信息", description = "字典信息") @Tag(name = "字典信息", description = "字典信息")
@CoolRestController(api = { "add", "delete", "update", "page", "list", "info" }) @CoolRestController(api = {"add", "delete", "update", "page", "list", "info"})
public class AdminDictInfoController extends BaseController<DictInfoService, DictInfoEntity> { public class AdminDictInfoController extends BaseController<DictInfoService, DictInfoEntity> {
@Override @Override
protected void init(HttpServletRequest request, JSONObject requestParams) { protected void init(HttpServletRequest request, JSONObject requestParams) {