基于Java的配置,以启用Spring安全匿名访问

我想启用“ROLE_ANONYMOUS”来允许匿名访问我的应用中的某些url。 我使用了以下配置。

@Override protected void configure(HttpSecurity http) throws Exception { http .requestCache() .requestCache(new NullRequestCache()).and() .anonymous().authorities("ROLE_ANONYMOUS").and() .exceptionHandling().and() .servletApi().and() .headers().cacheControl().and() .authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/profile/image").permitAll() .antMatchers("/favicon.ico").permitAll() .antMatchers("/resources/**").permitAll() //.antMatchers(HttpMethod.GET, "/login/**").permitAll() //.antMatchers(HttpMethod.GET, "/location/**").permitAll() .anyRequest().authenticated()/*.and() .apply(new SpringSocialConfigurer())*/; // custom Token based authentication based on the header previously given to the client //.addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService), UsernamePasswordAuthenticationFilter.class); } 

我的控制器看起来像:

 @RestController @RequestMapping(value="/login", produces="application/json") public class LoginController { @Secured( value={"ROLE_ANONYMOUS"}) @RequestMapping(method=RequestMethod.GET) public String get(){ return "hello"; } } 

但是当我尝试点击“/ login”时,我得到403拒绝访问权限错误。 请帮助我如何启用基于匿名访问的注释。

正如Faraj Farook所写,您必须允许访问您的登录页面URL。 你评论了相关的一行:

 @Override protected void configure(HttpSecurity http) throws Exception { http .anonymous() .authorities("ROLE_ANONYMOUS") .and() .headers() .cacheControl() .and() .authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/profile/image").permitAll() .antMatchers("/favicon.ico").permitAll() .antMatchers("/resources/**").permitAll() .antMatchers(HttpMethod.GET, "/login/**").permitAll() .anyRequest().authenticated() } 

但是如果你不想使用permitAll()你可以使用hasAuthority("ROLE_ANONYMOUS") 。 在这种情况下,您不需要使用@Secured( value={"ROLE_ANONYMOUS"})注释您的方法。

这应该可以解决您的问题。

 @Override protected void configure(HttpSecurity http) throws Exception { http ... .formLogin().loginPage("/login").permitAll() ... 

但是如果你不想使用permitAll而是坚持使用匿名用户(这对两种情况都会产生同样的效果,但如果你喜欢这种情况的话),那么在控制器中尝试一下。

 @Secured("ROLE_ANONYMOUS") @RequestMapping(method=RequestMethod.GET) public String get(){ ...