明确保护特定模式而不是忽略所有非安全模式
Explicitly secure a specific pattern instead of ignoring all non-secured patterns
我有一个应用程序,我只需要保护 /admin/ 页面。所有其他页面都没有登录、帐户或其他需要安全的功能。
根据其他问题和教程,我目前已经通过明确忽略所有不需要安全的路径来实现这一点,例如
web
.ignoring()
.antMatchers("/js/**");
web
.ignoring()
.antMatchers("/static/**");
web
.ignoring()
.antMatchers("/images/**");
web
.ignoring()
.antMatchers("/css/**");
web
.ignoring()
.antMatchers("/fonts/**");
这会使配置变得更大,并且无法完全清楚您要保护的内容,因为它只说明了例外情况。
有没有办法先明确禁用所有安全性,然后添加要激活它的模式?
忽略安全性(即使是 public 静态 URL)通常被认为是不好的做法,除非您有明确的理由这样做。请记住 Spring 安全性还有助于 Security HTTP Response Headers 确保您的应用程序安全。
考虑到这一点,将删除您拥有的忽略配置并仅更新您的安全授权规则。例如:
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/").hasRole("ADMIN")
.and()
.formLogin()
...
}
// ...
}
也就是说,如果您真的需要忽略除以 admin 开头的请求之外的所有请求,您可以使用正则表达式轻松执行此操作:
web
.ignoring()
.regexMatchers("^(?!/admin/).*");
您还可以注入自定义匹配器实现。 Spring Security 甚至提供以下开箱即用的功能:
RequestMatcher adminRequests = new AntPathRequestMatcher("/admin/**");
RequestMatcher notAdminRequests = new NegatedRequestMatcher(adminRequests);
web
.ignoring()
.requestMatchers(notAdminRequests);
我有一个应用程序,我只需要保护 /admin/ 页面。所有其他页面都没有登录、帐户或其他需要安全的功能。
根据其他问题和教程,我目前已经通过明确忽略所有不需要安全的路径来实现这一点,例如
web
.ignoring()
.antMatchers("/js/**");
web
.ignoring()
.antMatchers("/static/**");
web
.ignoring()
.antMatchers("/images/**");
web
.ignoring()
.antMatchers("/css/**");
web
.ignoring()
.antMatchers("/fonts/**");
这会使配置变得更大,并且无法完全清楚您要保护的内容,因为它只说明了例外情况。
有没有办法先明确禁用所有安全性,然后添加要激活它的模式?
忽略安全性(即使是 public 静态 URL)通常被认为是不好的做法,除非您有明确的理由这样做。请记住 Spring 安全性还有助于 Security HTTP Response Headers 确保您的应用程序安全。
考虑到这一点,将删除您拥有的忽略配置并仅更新您的安全授权规则。例如:
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/").hasRole("ADMIN")
.and()
.formLogin()
...
}
// ...
}
也就是说,如果您真的需要忽略除以 admin 开头的请求之外的所有请求,您可以使用正则表达式轻松执行此操作:
web
.ignoring()
.regexMatchers("^(?!/admin/).*");
您还可以注入自定义匹配器实现。 Spring Security 甚至提供以下开箱即用的功能:
RequestMatcher adminRequests = new AntPathRequestMatcher("/admin/**");
RequestMatcher notAdminRequests = new NegatedRequestMatcher(adminRequests);
web
.ignoring()
.requestMatchers(notAdminRequests);