【问题标题】:How to enable spring security for particular url如何为特定 url 启用 spring 安全性
【发布时间】:2018-05-21 12:16:04
【问题描述】:

我使用 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/ url 公开使用。

【问题讨论】:

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


【解决方案1】:

为什么不试试角色呢?

@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

【讨论】:

  • 我已经尝试过了,但没有运气,行为仍然相同。
  • 你调试哪一行失败了吗?更改顺序或删除这个 .antMatchers("/**").permitAll() 并逐行添加条件
【解决方案2】:
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");

非常适合我。

【讨论】:

    猜你喜欢
    • 2021-06-01
    • 2018-08-15
    • 2014-01-04
    • 2018-11-22
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    相关资源
    最近更新 更多