如何在@RequestMapping上允许匿名访问?

时间:2017-06-29 07:16:27

标签: java spring spring-security

如何定义@RequestMapping方法以明确允许匿名(未授权)访问?

以下操作不起作用,始终获取401 Unauthorized

@RequestMapping("/test")
@Secured(value={"ROLE_ANONYMOUS"})
public String test() {
    return "OK";
}

通常,使用spring-boot

按如下方式保护整个应用程序

security.basic.enabled=true

@Configuration
public class AuthConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }
}

2 个答案:

答案 0 :(得分:1)

您可以覆盖configure(HttpSecurity httpSecurity)方法并在那里定义规则:

@Configuration
public class AuthConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        httpSecurity.authorizeRequests()
           .antMatchers("/test")
           .permitAll();
        super.configure(http);
    }
}

答案 1 :(得分:0)

@Configuration
public class AuthConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        httpSecurity.authorizeRequests().regexMatcher("^((?!test).)*$").permitAll();
    }
}

我不确定test之前的斜线,但只是尝试这种负面的环视方法。