java - @PreAuthorize ("isAuthenticated()") 与 http.anyRequest().authenticated()

标签 java spring spring-security configuration authorization

这两种不同的安全方法有什么区别? 第一个依赖于配置 Spring Security 中的 HttpSecurity 对象。 。 第二个依赖于将 @PreAuthorize("isAuthenticated()") 放在每个方法或类上。

第一种情况:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest()
                .authenticated();
    }
}

第二种情况:

每个方法/类上的

@PreAuthorize("isAuthenticated()")

第一种方法看起来更好,因为您可以同时保护所有端点,并且使用 @PreAuthorize 需要更多工作。但这两者之间的实际区别是什么?

最佳答案

可以在 WebSecurityConfigurerAdapter 上授权所有请求,并在每个服务上使用 PreAuthorize 进行安全保护。

使用 WebSecurityConfigurerAdapter 的优点是可以概览您的安全访问。 但 @PreAuthorize 允许您进行更细粒度的安全处理。例如,只有当用户写过这篇文章时,您才可以判断他有编辑这篇文章的权限。

我认为在大型应用程序中,两者都使用是可以的。

关于java - @PreAuthorize ("isAuthenticated()") 与 http.anyRequest().authenticated(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50735968/

相关文章:

java - 为什么我的程序要添加一个新行?

java - 如何在Actor的onReceive方法中执行异步数据库插入?

java - ubuntu 通信链接失败时的 Mysql 和 java 连接问题

java - ActiveMQ:队列(具有并发消费者)和主题的正确配置

java - 如何使用 Spring Security SAML 配置远程发现?

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

spring - 我的 xml 配置有什么问题?

spring - ant.propertyFile每次都会更新评论

java - Spring 安全: get password in UserDetailsServiceMethod

java - Spring + hibernate : No Session Found For Current Thread