Spring Security
的默认安全配置指定路径不需要认证的话,是无法动态更新匹配 URL 白名单的规则;Nacos
随时更新发布新的配置 或者 通过从 Redis
/ 数据库 等方式获取到匹配 URL
白名单的规则;URL
白名单的加载,在匹配时时候根据自定义函数获取对应匹配数据;基于 Spring Security 5.7
进行改造的案例,其他版本可以作为参考,改造方法类似。
/**
* 资源服务器配置
*/
@Configuration
@AllArgsConstructor
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true, securedEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
private TokenStore tokenStore;
// 放在 Nacos 上的配置文件
private SecurityCommonProperties securityProperties;
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(SpringContextUtils.applicationName());
resources.tokenStore(tokenStore);
resources.authenticationEntryPoint(new SecurityAuthenticationEntryPoint());
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
// 根据 securityProperties 的 UrlWhiteArray 白名单放行部分 URL
.antMatchers(securityProperties.getUrlWhiteArray()).permitAll()
.anyRequest().authenticated();
}
}
Nacos
配置动态更新 URL
白名单通过
Nacos
修改白名单配置虽然是可以动态刷新SecurityCommonProperties
对应字段的数据,但是Spring Security
的白名单是不会刷新的。因为内容已经在启动应用时候加载进去了,后续并没有变化
自定义
org.springframework.security.web.util.matcher.RequestMatcher
LazyMvcRequestMatcher
代码import lombok.extern.slf4j.Slf4j;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.util.UrlPathHelper;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.function.Supplier;
import static java.util.stream.Collectors.toSet;
/**
* @author hdfg159
*/
@Slf4j
public class LazyMvcRequestMatcher implements RequestMatcher {
private final UrlPathHelper pathHelper = new UrlPathHelper();
private final PathMatcher pathMatcher = new AntPathMatcher();
// 获取白名单的 Java8 Supplier 函数
private final Supplier<Set<String>> patternsSupplier;
public LazyMvcRequestMatcher(Supplier<Set<String>> patternsSupplier) {
this.patternsSupplier = patternsSupplier;
}
/**
* 获取白名单列表
* @return {@code Set<String>}
*/
public Set<String> getPatterns() {
try {
return Optional.ofNullable(patternsSupplier)
.map(Supplier::get)
.map(patterns -> patterns.stream().filter(Objects::nonNull).filter(s -> !s.isBlank()).collect(toSet()))
.orElse(new HashSet<>());
} catch (Exception e) {
log.error("Get URL Pattern Error,Return Empty Set", e);
return new HashSet<>();
}
}
private boolean matches(String pattern, String lookupPath) {
boolean match = pathMatcher.match(pattern, lookupPath);
log.debug("Match Result:{},Pattern:{},Path:{}", match, pattern, lookupPath);
return match;
}
@Override
public MatchResult matcher(HttpServletRequest request) {
var patterns = getPatterns();
var lookupPath = pathHelper.getLookupPathForRequest(request);
for (String pattern : patterns) {
if (matches(pattern, lookupPath)) {
Map<String, String> variables = pathMatcher.extractUriTemplateVariables(pattern, lookupPath);
return MatchResult.match(variables);
}
}
return MatchResult.notMatch();
}
@Override
public boolean matches(HttpServletRequest request) {
var lookupPath = pathHelper.getLookupPathForRequest(request);
return getPatterns().stream().anyMatch(pattern -> matches(pattern, lookupPath));
}
}
Spring Security
安全配置写法案例import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
public abstract class DefaultResourceServerConfig extends ResourceServerConfigurerAdapter {
private final TokenStore store;
private final SecurityCommonProperties properties;
public DefaultResourceServerConfig(TokenStore store, SecurityCommonProperties properties) {
this.store = store;
this.properties = properties;
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(SpringContextUtils.applicationName());
resources.tokenStore(store);
resources.authenticationEntryPoint(new SecurityAuthenticationEntryPoint());
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
// 关键点配置在这里,通过使用自己实现的 RequestMatcher
.requestMatchers(new LazyMvcRequestMatcher(() ->
// 函数内实现获取白名单规则代码,可以通过 Nacos 动态刷新配置 、 读取 Redis 、 读取数据库等操作
properties.applicationDefaultWhitelistUrlPattern(SpringContextUtils.applicationName())
)).permitAll()
.anyRequest().authenticated();
}
}
上面代码的实现,是可以在匹配时候动态获取对应名单,从而达到动态刷新白名单的效果
注意:获取白名单函数内的代码逻辑尽量简单,不要编写执行时间长的代码,这样很容易影响应用的性能,每次路径匹配都会对函数进行调用,很容易成造成性能问题。
Spring Security
配置中自定义 org.springframework.security.web.util.matcher.RequestMatcher
(Spring Security
请求匹配器)Lambda
的延迟执行,对实时规则进行读取匹配