Spring Security 实现动态刷新 URL 白名单

Spring Security 实现动态刷新 URL 白名单

前言

  • 根据 Spring Security 的默认安全配置指定路径不需要认证的话,是无法动态更新匹配 URL 白名单的规则;
  • 现在我们的需求是通过 Nacos 随时更新发布新的配置 或者 通过从 Redis / 数据库 等方式获取到匹配 URL 白名单的规则;
  • 目标是能够自定义函数实现动态加载 URL 白名单的加载,在匹配时时候根据自定义函数获取对应匹配数据;

版本说明

基于 Spring Security 5.7 进行改造的案例,其他版本可以作为参考,改造方法类似。

实现

  1. 不能实现动态刷新的案例
/**
 * 资源服务器配置
 */
@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 的白名单是不会刷新的。因为内容已经在启动应用时候加载进去了,后续并没有变化

  • 需要通过重启应用才能生效,如果在生产环境或者开发环境,这个操作是十分不方便的
  1. 动态刷新实现

自定义 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();
    }
}

上面代码的实现,是可以在匹配时候动态获取对应名单,从而达到动态刷新白名单的效果

注意:获取白名单函数内的代码逻辑尽量简单,不要编写执行时间长的代码,这样很容易影响应用的性能,每次路径匹配都会对函数进行调用,很容易成造成性能问题。

总结

  1. Spring Security 配置中自定义 org.springframework.security.web.util.matcher.RequestMatcher (Spring Security 请求匹配器)
  2. 通过 函数式编程 的方式,就是 Lambda 的延迟执行,对实时规则进行读取匹配
  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security可以通过配置IP白名单来限制特定IP地址的访问。实现IP白名单机制的步骤如下: 1. 创建一个IP白名单过滤器,该过滤器用于过滤请求。在过滤器中,获取请求的IP地址,并将其与白名单列表进行比较。 ```java public class IpFilter extends OncePerRequestFilter { private final List<String> whitelist = Arrays.asList("192.168.1.100", "192.168.1.101"); @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String ipAddress = request.getRemoteAddr(); if (whitelist.contains(ipAddress)) { filterChain.doFilter(request, response); } else { response.setStatus(HttpStatus.FORBIDDEN.value()); } } } ``` 2. 在Spring Security配置文件中配置该过滤器,并将其添加到过滤器链中。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private IpFilter ipFilter; @Override protected void configure(HttpSecurity http) throws Exception { http .addFilterBefore(ipFilter, BasicAuthenticationFilter.class) .authorizeRequests() .anyRequest().authenticated() .and() .httpBasic(); } } ``` 在上述配置中,我们将IP过滤器添加到了基本认证过滤器之前,以确保所有请求都受到IP白名单的限制。 3. 测试IP白名单机制。使用一个不在白名单列表中的IP地址进行访问,应该会返回HTTP 403 Forbidden状态码。而使用白名单列表中的IP地址进行访问,应该可以正常访问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值