Spring Security 實現(xiàn)動態(tài)刷新 URL 白名單
前言
- 根據(jù)
Spring Security
的默認安全配置指定路徑不需要認證的話漂羊,是無法動態(tài)更新匹配 URL 白名單的規(guī)則; - 現(xiàn)在我們的需求是通過
Nacos
隨時更新發(fā)布新的配置 或者 通過從Redis
/ 數(shù)據(jù)庫 等方式獲取到匹配URL
白名單的規(guī)則痘拆; - 目標是能夠自定義函數(shù)實現(xiàn)動態(tài)加載
URL
白名單的加載,在匹配時時候根據(jù)自定義函數(shù)獲取對應(yīng)匹配數(shù)據(jù)新啼;
版本說明
基于 Spring Security 5.7
進行改造的案例,其他版本可以作為參考础嫡,改造方法類似氛谜。
實現(xiàn)
- 不能實現(xiàn)動態(tài)刷新的案例
/**
* 資源服務(wù)器配置
*/
@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()
// 根據(jù) securityProperties 的 UrlWhiteArray 白名單放行部分 URL
.antMatchers(securityProperties.getUrlWhiteArray()).permitAll()
.anyRequest().authenticated();
}
}
- 案例是我們項目上的代碼掏觉,不能通過發(fā)布
Nacos
配置動態(tài)更新URL
白名單
通過
Nacos
修改白名單配置雖然是可以動態(tài)刷新SecurityCommonProperties
對應(yīng)字段的數(shù)據(jù),但是Spring Security
的白名單是不會刷新的值漫。因為內(nèi)容已經(jīng)在啟動應(yīng)用時候加載進去了澳腹,后續(xù)并沒有變化
- 需要通過重啟應(yīng)用才能生效,如果在生產(chǎn)環(huán)境或者開發(fā)環(huán)境杨何,這個操作是十分不方便的
- 動態(tài)刷新實現(xiàn)
自定義
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 函數(shù)
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()
// 關(guān)鍵點配置在這里酱塔,通過使用自己實現(xiàn)的 RequestMatcher
.requestMatchers(new LazyMvcRequestMatcher(() ->
// 函數(shù)內(nèi)實現(xiàn)獲取白名單規(guī)則代碼,可以通過 Nacos 動態(tài)刷新配置 危虱、 讀取 Redis 羊娃、 讀取數(shù)據(jù)庫等操作
properties.applicationDefaultWhitelistUrlPattern(SpringContextUtils.applicationName())
)).permitAll()
.anyRequest().authenticated();
}
}
上面代碼的實現(xiàn),是可以在匹配時候動態(tài)獲取對應(yīng)名單埃跷,從而達到動態(tài)刷新白名單的效果
注意:獲取白名單函數(shù)內(nèi)的代碼邏輯盡量簡單蕊玷,不要編寫執(zhí)行時間長的代碼,這樣很容易影響應(yīng)用的性能捌蚊,每次路徑匹配都會對函數(shù)進行調(diào)用集畅,很容易成造成性能問題。
總結(jié)
- 在
Spring Security
配置中自定義org.springframework.security.web.util.matcher.RequestMatcher
(Spring Security
請求匹配器) - 通過 函數(shù)式編程 的方式缅糟,就是
Lambda
的延遲執(zhí)行,對實時規(guī)則進行讀取匹配