java - 如何允许匿名访问@RequestMapping?

标签 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());
    }
}

最佳答案

您可以重写 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);
    }
}

关于java - 如何允许匿名访问@RequestMapping?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44818653/

相关文章:

java - LinkedList与堆栈

java - Spring boot FF4j ff4j-spring-boot-starter 不包括 swagger 文档

java - 使用 Spring 和 AspectJ 拦截私有(private)方法

java - nginx tomcat7错误: - “recv() failed (104: Connection reset by peer) while reading response header from upstream”

spring - 使用 @OneToMany 或 @ManyToMany 定位未映射的类 : com. example.soasec.entities.User.roles[com.example.soasec.entities.Role]

java - Spring security UserDetailsS​​ervice 不工作

java - 使用 Oracle 的 Spring Boot 2.0 分页不起作用

java - 运行项目时的TestNG问题

java - spring中@component的xml配置表示是什么

java - 如何将我的新 Spring 框架 Web 应用程序与启用了单点登录 (SSO) 的 Struts 框架 Web 应用程序链接