如何为特定URL启用spring security

时间:2018-05-21 12:16:05

标签: java spring spring-mvc spring-boot spring-security

我正在使用spring security,我的配置是

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.
        authorizeRequests()
            .antMatchers("/**").permitAll()
            .antMatchers("/admin/**").hasAuthority("ADMIN").anyRequest().authenticated()
            .and().csrf().disable().formLogin().loginPage("/adminlogin").failureUrl("/adminlogin?error=true")
            .defaultSuccessUrl("/admin/dashboard")
            .usernameParameter("email")
            .passwordParameter("password")
            .and().logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/adminlogin?logout=true").and().exceptionHandling()
            .accessDeniedPage("/accessdenied");
}

现在我想要实现的是所有链接都可以在没有任何安全性的情况下访问,但链接以/ admin / **开头只允许用户使用角色" admin"。

但现在它允许每个人使用/ admin / **。

任何建议。

我尝试了很多来自stackoverflow的解决方案,即How to fix role in Spring Security?,但没有运气。行为保持不变,它允许偶数/ admin / urls公开使用。

2 个答案:

答案 0 :(得分:0)

为什么不尝试角色?

@Configuration
@EnableWebSecurity
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          .authorizeRequests()
          .antMatchers("/admin/**").hasRole("ADMIN");
    }
   }

参考:http://www.baeldung.com/spring-security-expressions-basic

答案 1 :(得分:0)

http
    .csrf().disable()      
    .httpBasic().and()
    .authorizeRequests()
        .antMatchers("/admin/**").hasAuthority("ADMIN")
        .antMatchers("/**").permitAll()
        .anyRequest().authenticated()
        .and()
    .formLogin()
    .loginPage("/adminLogin").failureUrl("/adminLogin?error=true")
    .defaultSuccessUrl("/admin/dashboard")
    .usernameParameter("email")
    .passwordParameter("password")
    .and().logout()
    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
    .logoutSuccessUrl("/adminLogin?logout=true").and().exceptionHandling()
    .accessDeniedPage("/accessdenied");

非常适合我。