Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

关于 spring security 配置问题

想实现只对 /actuator/** 路径会进行鉴权,并且在源 ip 为内网的时候放行,否则需要通过 HTTP basic 认证

目前的配置可以实现内网放行,代码如下:

http.antMatcher("/actuator/**")
                .authorizeRequests()
                .anyRequest()
                .access("hasIpAddress('::1')" +
                        " or hasIpAddress('127.0.0.1')" +
                        " or hasIpAddress('10.0.0.0/8')" +
                        " or hasIpAddress('172.16.0.0/12')" +
                        " or hasIpAddress('192.168.0.0/16')")
                .and()
                .httpBasic();

但是这样的话会导致配置文件中定义的用户名和密码失效:

spring.security.user.name=admin
spring.security.user.password=123456

之前不做 ip 白名单的时候配置的用户密码可以生效的:

http.antMatcher("/actuator/**").authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .httpBasic();

大佬们帮忙看看应该怎么配置,或者有没有什么最简单的办法能做自定义的权限校验。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

把路径设置未匿名可访问,在匿名过滤器后面添加一个类似于匿名过滤器,在其中校验路径,如果符合 检查 ip,如果符合,不做什么,如果不符合,就把 匿名用户删除 。`

private boolean isPath(ServletRequest req){
    // ...
    return false;
}

private boolean isNotMyIp(ServletRequest req){
    // ...
    return false;
}

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    if(isPath(req) && isNotMyIp(req)){
        if (SecurityContextHolder.getContext().getAuthentication() != null) {
            SecurityContextHolder.getContext().setAuthentication(null);
        }
    }

    chain.doFilter(req, res);
}

`
具体可以参照``
AnonymousAuthenticationFilter


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...