Spring Security Java Config-请求URL的动态IP列表



我有两种配置。第一个希望实现来自(/api/**)的所有请求必须仅来自一个确定的ip。

喜欢关注。。。

.authorizeRequests().antMatchers("/api/**").hasIpAddress("dynamic List of IPs");

应检查IP是否存储在数据库中,否则将拒绝访问。

而secound配置负责处理其余部分。

@EnableWebSecurity
public class AppSecurityConfig {
@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(new CustomUserDetailsService()).passwordEncoder(new Md5PasswordEncoder());
}
@Configuration
@Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .headers().disable()
                .authorizeRequests().antMatchers("/api/**").hasIpAddress("dynamic List of IPs");
    }
}
@Configuration
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().maximumSessions(1)
                .expiredUrl("/error/expired.xhtml").and()
                .invalidSessionUrl("/Anmeldung.xhtml?check=invalid");
        http
                .csrf().disable()
                .headers().disable()
                .formLogin().loginPage("/Anmeldung/").loginProcessingUrl("/j_spring_security_check").successHandler(new CustomAuthenticationSuccessHandler())
                .failureUrl("/Anmeldung.xhtml?check=error").usernameParameter("j_username").passwordParameter("j_password")
                .and()
                .exceptionHandling().accessDeniedPage("/error/403.xhtml")
                .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/Anmeldung.xhtml?check=logout").invalidateHttpSession(false).deleteCookies("JSESSIONID").permitAll();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry interceptUrlRegistry = http.authorizeRequests();
        interceptUrlRegistry.antMatchers("/Administrator/*").hasAnyAuthority("ROLE_ADMIN");
        interceptUrlRegistry.antMatchers("/*").hasAnyAuthority("ROLE_USER");
        interceptUrlRegistry.antMatchers("/Anmeldung/index.xhtml").anonymous();
        interceptUrlRegistry.antMatchers("/template/*").denyAll();
        interceptUrlRegistry.antMatchers("/resources/**").permitAll();
    }
}
}

谢谢你的帮助。

您可以像下面引用的代码一样,在循环内部动态配置httpsecurity对象。

for (Entry<String, String> entry : hasmapObject) {
                String url = entry.getKey().trim();
                String ips= entry.getValue().trim();
    http.authorizeRequests().and().authorizeRequests().antMatchers(url).hasIpAddress(ips);
            }

这对我很有效。hashmap对象有一个url的动态列表和相应的ip来提供访问权限。

"http.authorizeRequests().and()"这个and()需要缩进,就像我们在xml配置中配置xml中的http子元素一样。

如果这有帮助,请告诉我。

最新更新