【问题标题】:Spring security WebSecurityConfigurerAdapter configuration issueSpring security WebSecurityConfigurerAdapter 配置问题
【发布时间】:2018-02-02 21:49:46
【问题描述】:

在以下扩展 WebSecurityConfigurerAdapter 的类中,我覆盖了 configure(HttpSecurity) 方法。

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter{

@Autowired
public void configureAuth(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .inMemoryAuthentication()
            .withUser("fabio")
            .password("123")
            .roles("ADMIN")
        .and()
            .withUser("joe")
            .password("123")
            .roles("GUEST");

}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
                .antMatchers("/post/list").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            .and()
            .formLogin()
            .and()
            .logout();
}
}

有了这个我应该能够进入localhost:8080/post/list页面而不必提交用户登录,因为它有.permitAll(),但是当我尝试进入它时它总是提示登录页面之前,只有之后我输入以前的凭据,我可以查看它。我该如何解决这个问题?

控制器类

@RestController
@RequestMapping("/post")
public class HomeController {

    @Secured("ROLE_GUEST")
    @RequestMapping("/list")
    public String list(){
    return "list...";
    }

    @Secured("ROLE_USER")
    @RequestMapping("/drafts")
    public String drafts(){
        return "drafts...";
    }

    @Secured({"ROLE_ADMIN","ROLE_USER"})
    @RequestMapping("/add")
    public String add(){
        return "adding...";
    }

}

【问题讨论】:

  • 试试.antMatchers("/post/list**").permitAll()
  • 不行

标签: java spring spring-security


【解决方案1】:

根据@RequestMapping 定义存在冲突,因为它由注释@Secured("ROLE_GUEST") 保护,但您还需要使用.permitAll() 配置访问它。

选项 1:只需删除 @Secured("ROLE_GUEST") 以便让 .permitAll() 完成工作。

选项 2:在 @RequestMapping("/list") 上使用 @Secured("ROLE_ANONYMOUS") 而不是 @Secured("ROLE_GUEST")。在Spring Documentation中可以看到ROLE_ANONYMOUS的定义


这取决于/post/list 之后的路径值。如何根据路径值定义antMatchers,请看以下示例。

localhost:8080/post/list = .antMatchers( "/post/list").permitAll()

localhost:8080/post/list/stuff = .antMatchers( "/post/list/**").permitAll()

localhost:8080/post/listlocalhost:8080/post/list1234

= .antMatchers( "/post/list**").permitAll()

有关更多信息,请访问AnthPathMatcher 文档和HttpSecurity

【讨论】:

  • 就是这个localhost:8080/post/list,它不应该与我的代码一起使用吗?
  • 是的,这就是它的工作原理,只要确定一些事情,@RequestMapping 处理程序上的路径是如何声明的?你能提供吗?并访问此帖子stackoverflow.com/questions/29721098/…
猜你喜欢
  • 2016-12-17
  • 1970-01-01
  • 2020-03-25
  • 2015-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-13
  • 2016-03-25
相关资源
最近更新 更多