在以下扩展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...";
}
}
答案 0 :(得分:0)
根据@RequestMapping
定义存在冲突,因为它受到注释@Secured("ROLE_GUEST")
的保护,但您还需要使用.permitAll()
配置进行访问。
选项1:只需移除@Secured("ROLE_GUEST")
即可让.permitAll()
完成工作。
选项2:在@Secured("ROLE_ANONYMOUS")
而不是@RequestMapping("/list")
上使用@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/list
,localhost:8080/post/list1234
= .antMatchers( "/post/list**").permitAll()
有关详情,请访问AnthPathMatcher文档和HttpSecurity