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

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

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

  1. SecurityFilterChain basicAuthSecurityFilterChain(HttpSecurity http) throws Exception {
  2. http
  3. .authorizeHttpRequests((authorize) -> authorize
  4. .requestMatchers("/test").authenticated()
  5. .anyRequest().permitAll()
  6. )
  7. .csrf().disable()
  8. .httpBasic();
  9. return http.build();
  10. }

IP地址筛选器:

  1. SecurityFilterChain ipSecurityFilterChain(HttpSecurity http) throws Exception {
  2. http
  3. .authorizeHttpRequests((authorize) -> authorize
  4. .requestMatchers("/test").access(hasIpAddress("127.0.0.1"))
  5. .anyRequest().permitAll()
  6. )
  7. .csrf().disable();
  8. return http.build();
  9. }
  10. private AuthorizationManager<RequestAuthorizationContext> hasIpAddress(String ipAddress) {
  11. IpAddressMatcher ipAddressMatcher = new IpAddressMatcher(ipAddress);
  12. return (authentication, context) -> {
  13. HttpServletRequest request = context.getRequest();
  14. return new AuthorizationDecision(ipAddressMatcher.matches(request));
  15. };
  16. }

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

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

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

flseospp

flseospp1#

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

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

与这些静态导入一起:

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

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

  1. http.authorizeHttpRequests()
  2. .requestMatchers("/test").access(allOf(authenticated(), hasIpAddress("127.0.0.1")))
  3. .anyRequest().permitAll();
展开查看全部

相关问题