Spring Web安全仅限制单页

时间:2017-11-03 08:45:30

标签: java spring spring-mvc spring-security

我使用的是Spring网络安全,下面的代码限制所有网页除了所列的内容,例如资源和app.html

如何将此更改为允许除我明确指定的所有页面以外的所有页面?

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http    .authorizeRequests()
                .antMatchers("/resources/**", "/registration", "/app.html").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }
}

我从这里得到了代码:https://spring.io/blog/2013/07/03/spring-security-java-config-preview-web-security/但我无法看到问题的答案。

由于

2 个答案:

答案 0 :(得分:1)

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/mysupersecureurl/**").authenticated()
                .anyRequest().permitAll()
                .and()
                .csrf().disable();
    }

这将保护您的mysupersecureurl并让其他网址开放(即permitAll())。

另外作为奖励,您可以禁用csrf,如果您正在对mysupersecureurl上的其他网址发帖。这是您可以保留或删除的选项。

答案 1 :(得分:0)

尝试anyRequest().permitAll()允许所有网页/ apis

antMatchers("/api/yourAPI").authenticated()

(或antMatchers("/api/yourAPI").hasAuthority(AuthoritiesConstants.ADMIN)针对特定用户(此处为admin))限制您的网页

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http    .authorizeRequests()
                .anyRequest().permitAll()
                .antMatchers("/resources/**", "/registration", "/app.html").permitAll()
                .antMatchers("/api/yourAPI").authenticated()
                // or .antMatchers("/api/yourAPI").hasAuthority(AuthoritiesConstants.ADMIN)
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }
}