2

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

像关注...

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

检查IP是否存入数据库,否则拒绝访问。

第二个配置负责其余的工作。

@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();
    }
}
}

谢谢你的帮助。

4

1 回答 1

0

您可以在 for 循环中动态配置 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 的动态列表及其对应的 ips 以提供访问权限。

“http.authorizeRequests().and()” 这个and() 是需要缩进的,就像我们在xml 配置中使用的那样来配置XML 中的http 子元素。

请让我知道这可不可以帮你。

于 2018-02-07T12:17:06.813 回答