在springboot 3中使用基本auth和附加条件保护端点

pxy2qtax  于 2023-09-29  发布在  Spring
关注(0)|答案(1)|浏览(123)

我想用基本身份验证保护一个端点,并只允许来自特定IP地址的请求。基本身份验证筛选器:

SecurityFilterChain basicAuthSecurityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((authorize) -> authorize
                                               .requestMatchers("/test").authenticated()
                                               .anyRequest().permitAll()
                                      )
                .csrf().disable()
                .httpBasic();

        return http.build();
    }

IP地址筛选器:

SecurityFilterChain ipSecurityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((authorize) -> authorize
                                               .requestMatchers("/test").access(hasIpAddress("127.0.0.1"))
                                               .anyRequest().permitAll()
                                      )
                .csrf().disable();

        return http.build();
    }

private AuthorizationManager<RequestAuthorizationContext> hasIpAddress(String ipAddress) {
        IpAddressMatcher ipAddressMatcher = new IpAddressMatcher(ipAddress);
        return (authentication, context) -> {
            HttpServletRequest request = context.getRequest();
            return new AuthorizationDecision(ipAddressMatcher.matches(request));
        };
    }

问题是如何将这些解决方案结合起来。我可以用更老的Spring

.access("isAuthenticated() and hasIpAddress('127.0.0.1')")

但是现在这个方法只接受AuthorizationManager而不是String。

flseospp

flseospp1#

您可以创建一个helper方法,创建一个与特定IP匹配的AuthorizationManager

private AuthorizationManager<RequestAuthorizationContext> hasIpAddress(String ipAddress) {
    IpAddressMatcher ipAddressMatcher = new IpAddressMatcher(ipAddress);
    return (authentication, context) -> {
        HttpServletRequest request = context.getRequest();
        return new AuthorizationDecision(ipAddressMatcher.matches(request));
    };
}

与这些静态导入一起:

import static org.springframework.security.authorization.AuthenticatedAuthorizationManager.authenticated;
import static org.springframework.security.authorization.AuthorizationManagers.allOf;

然后,您可以将代码抛光为:

http.authorizeHttpRequests()
    .requestMatchers("/test").access(allOf(authenticated(), hasIpAddress("127.0.0.1")))
    .anyRequest().permitAll();

相关问题