我想用基本身份验证保护一个端点,并只允许来自特定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。
1条答案
按热度按时间flseospp1#
您可以创建一个helper方法,创建一个与特定IP匹配的
AuthorizationManager
:与这些静态导入一起:
然后,您可以将代码抛光为: