我在Spring Boot 2中找到了一个允许请求的cookbook:

@Override
public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/**")
            .access("hasIpAddress('127.0.0.1') or hasIpAddress('::1') or isAuthenticated()")  // 127.0.0.1 and localhost do not need to authenticate on any url
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .permitAll();
}

然而,我无法找到如何在Spring Boot3中实现它,在那里没有access个接受字符串的方法,我也没有找到相应的AuthorizationManager实现来做我需要的事情.

如何在Spring Boot3中只允许本地主机?

推荐答案

根据documentation

您应该这样做:

  @Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

       ...
        IpAddressMatcher hasIpAddress = new IpAddressMatcher("127.0.0.1");
        
        request.authorizeHttpRequests(requestMatcherRegistry -> {
          requestMatcherRegistry.requestMatchers("/path/**").access(((authentication, object) ->
              new AuthorizationDecision(hasIpAddress.matches(object.getRequest()))
          ));
          requestMatcherRegistry.anyRequest().denyAll();
        });
    ...
    return request.build();

Java相关问答推荐

将linkedHashMap扩展到Java中的POJO类

路径映射未发生

调用引发泛型异常的泛型方法时出现编译错误

为什么在maven中,getLast方法不适用于List?

具有阻塞方法的开源库是否应该为执行提供异步选项?

解释左移在Java中的工作原理

try 判断可选参数是否为空时出现空类型安全警告

使用Jolt将字段转换为列表

MimeMessage emlMessage=new MimeMessage(Session,emlInputStream);抛出InvocationTargetException

S,要对Java复制构造函数深度克隆所有属性进行单元测试,最可靠的方法是什么?

带有Health Check的Spring Boot BuildPack打破了本机映像构建过程

STREAMS减少部分结果的问题

在应用getCellFormula()时,Excel引用中的文件名始终为";[1]";使用Apache POI()

在整数列表中查找和可被第三个整数整除的对时出现无法解释的RunTimeError

基于Java中mm/dd/yy格式的最近日期对数组列表进行排序

从字节数组切换到JakartaMail org.springframework.mail.javamail.JavaMailSender InputStreamResource

如何在MPAndroidChart中的条形图上正确添加标签

ReturnedRect在升级后反转

可以';不要在Intellij IDEA中使用最新的Java版本(JDK 21)

Hibernate 命名策略导致 Java Spring Boot 应用程序中出现未知列错误