spring - 如何在 Spring Boot 中使用 IPwhitelisting 和 OAuth2?
问题描述
我在我的 Spring Boot 应用程序中使用 OAuth2,并且我想将 IP 白名单用于 IP 地址范围。即我想让白名单用户在不提供令牌的情况下访问特定资源。我有大量列入白名单的 IP,并且我正在使用 Oauth2 令牌验证,因此我有一个资源服务器。我想首先使用 IP 白名单,如果失败,用户应该拥有有效的令牌才能访问资源。你能告诉我我该怎么做吗?
解决方案
在 Spring Security 中,您可以使用安全配置类中的方法 hasIpAddress 配置您的特定端点和白名单。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/**").hasIpAddress("11.11.11.11")
.anyRequest().authenticated()
.and()
.formLogin().permitAll();
}
}
如果您有多个 IP 地址,那么您可以通过这种方式使用
http
.authorizeRequests()
.antMatchers("/api/**").access(
"hasIpAddress('10.0.0.0/16') or hasIpAddress('127.0.0.1/32')")
对于资源服务器,您可以在 @EnableResourceServer 类中执行此操作,并且可以使用相同的配置方法来设置 Ipwhitelisting,如下所示
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatcher(new OAuthRequestedMatcher())
.anonymous().disable().authorizeRequests();
http
.authorizeRequests()
.antMatchers("/api/**").access("hasIpAddress('10.0.0.0/16') or hasIpAddress('127.0.0.1/32')");
}
}
现在,既然您已经提到您有许多 IP 地址,您可以在属性文件 (application.properties) 中列出一个列表,并且在应用程序启动时,您可以遍历这些以构建必须在访问方法中传递的参数字符串.
推荐阅读
- hpc - Microsoft HPC 默认作业电子邮件设置/通知
- ios - 在 iOS 上使用 Google Maps/Places SDK 检索城市的地点 ID
- javascript - ReactJS - Child 的 onClick 事件调用父方法,但范围不是我所期望的
- r - 如何绘制具有上限的积分函数作为R中的另一个函数?
- c# - RichTextBox 用中文显示结果?
- html - Materialize CSS - 大屏幕上主要内容旁边的 Sidenav
- python - 使用 Python 测试与服务器的 telnet 连接
- javascript - 在 javascript 中使 Object.values O(1)
- syslog - 让 Cisco ASA 被摄取到 CommonSecurityLog 数据表的问题
- android - 'apktool' 不是内部或外部命令、可运行程序或批处理文件