spring - @PreAuthorize(permitAll) 仍然需要身份验证

我的 Repository 中有以下示例方法(带有 @RepositoryRestResource 注释):

@Override
@PreAuthorize("permitAll")
@PostAuthorize("permitAll")
public Iterable<User> findAll();

但是当我将那些 permitAll 注释添加到整个存储库接口(interface)时,我仍然收到 401 Unauthorized 事件。

我把它作为我的 WebSecurityConfigurerAdapter:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().fullyAuthenticated().and().httpBasic().and().csrf().disable();
    }
}

我想这优先于那些方法注释,但我不知道如何解决这个问题。

最佳答案

在网络安全过滤器之后应用方法安全性。

由于您的配置中有 anyRequest().fullyAuthenticated(),因此您的 findAll 方法将永远不会被命中。 anyRequest().fullyAuthenticated() 表示所有尝试访问没有完全用户身份验证的 Web 端点的所有尝试都将失败。

来自 JavaDoc

Specify that URLs are allowed by users who have authenticated and were not "remembered".

你需要在你的网络安全中添加一个额外的路径,比如。

protected void configure(final HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .anyRequest().fullyAuthenticated()
            .antMatchers(HttpMethod.GET, '/somePath').permitAll()
         .and()
            .httpBasic()
         .and()
            .csrf().disable();
}

https://stackoverflow.com/questions/33541678/

相关文章:

java - Spring Boot + Spring Data Multi-Tenancy

spring - 以编程方式重启 Spring Boot 应用程序

java - Spring MVC 3.2 - 错误页面的内容协商?

java - Spring配置继承和@Import的区别

java - 使用spring boot(安全)和keycloak启用角色身份验证?

Java - 避免创建空的子类和接口(interface)或生成 Java 源代码模板

java - 单个 hibernate session 中的多个事务(使用 Spring)

spring - Spring JUnit 测试中的自动模拟实例化

java - Spring 验证与 Hibernate 验证

java - 运行 find 会抛出一个 Detached 实体传递给持久异常