基于Java的配置,支持spring安全匿名访问

基于Java的配置,支持spring安全匿名访问,java,spring,spring-mvc,spring-security,Java,Spring,Spring Mvc,Spring Security,我想启用“ROLE\u ANONYMOUS”以允许匿名访问我应用程序中的某些URL。我使用了下面的配置 @Override protected void configure(HttpSecurity http) throws Exception { http .requestCache() .requestCache(new NullRequestCache()).and() .anonymous().authorities("RO

我想启用“ROLE\u 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";
    }
}
但当我尝试点击“/登录”时,我得到403拒绝访问错误。
请帮助我如何启用基于批注的匿名访问。

这将解决您的问题

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        ...
        .formLogin().loginPage("/login").permitAll()
        ...
但是,如果您不喜欢使用permitAll,而是坚持使用匿名roled用户(这对两种情况都会有相同的效果,但如果这是您喜欢的),那么请在控制器中尝试此操作

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

正如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()
,您可以使用
hasaauthority(“ROLE\u ANONYMOUS”)
。在这种情况下,您不需要使用
@Secured(value={“ROLE\u ANONYMOUS”})

谢谢@Faraj Farook。但正如我所说,我们只需要使用ROLE_ANONYMOUS。因为我有300多个不同的动作要标记为匿名。