Spring Security 實現(xiàn)動態(tài)刷新 URL 白名單

Spring Security 實現(xiàn)動態(tài)刷新 URL 白名單

前言

  • 根據(jù) Spring Security 的默認安全配置指定路徑不需要認證的話,是無法動態(tài)更新匹配 URL 白名單的規(guī)則;
  • 現(xiàn)在我們的需求是通過 Nacos 隨時更新發(fā)布新的配置 或者 通過從 Redis / 數(shù)據(jù)庫 等方式獲取到匹配 URL 白名單的規(guī)則;
  • 目標(biāo)是能夠自定義函數(shù)實現(xiàn)動態(tài)加載 URL 白名單的加載,在匹配時時候根據(jù)自定義函數(shù)獲取對應(yīng)匹配數(shù)據(jù);

版本說明

基于 Spring Security 5.7 進行改造的案例,其他版本可以作為參考,改造方法類似。

實現(xiàn)

  1. 不能實現(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)境,這個操作是十分不方便的
  1. 動態(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é)

  1. Spring Security 配置中自定義 org.springframework.security.web.util.matcher.RequestMatcher (Spring Security 請求匹配器)
  2. 通過 函數(shù)式編程 的方式,就是 Lambda 的延遲執(zhí)行,對實時規(guī)則進行讀取匹配
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容