1. Overview
1.概述
The Spring Security framework provides the WebSecurity and HttpSecurity classes to provide both global and resource-specific mechanisms to restrict access to APIs and assets. The WebSecurity class helps to configure security at a global level, while HttpSecurity provides methods to configure security for a specific resource.
Spring安全框架提供了WebSecurity和HttpSecurity类,以提供全局和特定于资源的机制来限制对API和资产的访问。WebSecurity 类有助于在全局级别配置安全性,而 HttpSecurity 则提供了为特定资源配置安全性的方法。
In this tutorial, we’ll look in detail at the key usage of HttpSecurity and WebSecurity. Also, we’ll see the differences between the two classes.
在本教程中,我们将详细介绍 HttpSecurity 和 WebSecurity 的主要用法。此外,我们还将了解这两个类之间的区别。
2. HttpSecurity
2.Http安全</em
The HttpSecurity class helps to configure security for specific HTTP requests.
HttpSecurity 类有助于为特定 HTTP 请求配置安全性。
Also, it permits using the requestMatcher() method to restrict security configuration to a specific HTTP endpoint.
此外,它还允许使用 requestMatcher() 方法将安全配置限制到特定 HTTP 端点。
Furthermore, it provides flexibility to configure authorization for a specific HTTP request. We can create a role-based authentication with the hasRole() method.
此外,它还提供了为特定 HTTP 请求配置授权的灵活性。我们可以使用 hasRole() 方法创建基于角色的身份验证。
Here’s an example code that uses the HttpSecurity class to restrict access to “/admin/**“:
下面是一个使用 HttpSecurity 类限制访问”/admin/**“的示例代码:
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authorize) -> authorize.requestMatchers("/admin/**")
.authenticated()
.anyRequest()
.permitAll())
.formLogin(withDefaults());
return http.build();
}
In the code above, we use the HttpSecurity class to restrict access to the “/admin/**” endpoint. Any request made to the endpoint will require authentication before access is granted.
在上面的代码中,我们使用 HttpSecurity 类来限制对”/admin/**“端点的访问。向该端点发出的任何请求都需要经过身份验证后才能被允许访问。
Furthermore, HttpSecurity provides a method to configure authorization for a restricted endpoint. Let’s modify our example code to permit only a user with an admin role to access the “/admin/**” endpoint:
此外,HttpSecurity 还提供了一种为受限端点配置授权的方法。让我们修改示例代码,只允许具有管理员角色的用户访问”/admin/**“端点:
// ...
http.authorizeHttpRequests((authorize) -> authorize.requestMatchers("/admin/**").hasRole("ADMIN")
// ...
Here, we provide more layers of security to the request by allowing access to the endpoint only for users with the “ADMIN” role.
在这里,我们只允许具有 “ADMIN “角色的用户访问端点,从而为请求提供了更多层次的安全性。
Additionally, the HttpSecurity class helps with configuring CORS and CSRF protection in Spring Security.
此外,HttpSecurity 类还有助于在 Spring Security 中配置 CORS 和 CSRF 保护。
3. WebSecurity
3.网络安全</em
The WebSecurity class helps to configure security at a global level in a Spring application. We can customize WebSecurity by exposing the WebSecurityCustomizer bean.
WebSecurity 类有助于在 Spring 应用程序中配置全局级别的安全性。我们可以通过公开 WebSecurityCustomizer bean 来定制 WebSecurity 。
Unlike the HttpSecurity class, which helps configure security rules for specific URL patterns or individual resources, WebSecurity configuration applies globally to all requests and resources.
HttpSecurity类有助于为特定 URL 模式或单个资源配置安全规则,而 WebSecurity 配置则不同,它适用于全局的所有请求和资源。
Furthermore, it provides methods to debug logging for Spring Security filters, ignore security checks for certain requests and resources, or configure a firewall for a Spring application.
此外,它还提供了为 Spring Security 过滤器调试日志、忽略某些请求和资源的安全检查或为 Spring 应用程序配置防火墙的方法。
3.1. The ignoring() Method
3.1.ignoring() 方法
Additionally, the WebSecurity class provides a method named ignoring(). The ignoring() method helps Spring Security to ignore an instance of a RequestMatcher. It’s recommended that register requests are of only static resources.
此外,WebSecurity类还提供了一个名为ignoring()的方法。ignoring() 方法可帮助 Spring Security 忽略 RequestMatcher 的实例。建议仅注册静态资源请求。
Here’s an example that uses the ignoring() method to ignore static resources in a Spring application:
下面是一个使用 ignoring() 方法忽略 Spring 应用程序中静态资源的示例:
@Bean
WebSecurityCustomizer ignoringCustomizer() {
return (web) -> web.ignoring().requestMatchers("/resources/**", "/static/**");
}
Here, we use the ignoring() method to bypass static resources from a security check.
在这里,我们使用 ignoring() 方法绕过静态资源的安全检查。
Notably, Spring advises that the ignoring() method shouldn’t be used for dynamic requests but only for static resources because it bypasses the Spring Security filter chain. This is recommended for static assets like CSS, images, etc.
值得注意的是,Spring 建议不要将 ignoring() 方法用于动态请求,而仅用于静态资源,因为它会绕过 Spring Security 过滤链。建议对 CSS、图像等静态资产使用该方法。
However, dynamic requests need to pass through authentication and authorization to provide different access rules because they carry sensitive data. Also, if we ignore dynamic endpoints completely, we lose total security control. This could open an application for different attacks like CSRF attacks or SQL injection.
但是,动态请求需要通过身份验证和授权,以提供不同的访问规则,因为它们携带敏感数据。此外,如果我们完全忽略动态端点,就会失去完全的安全控制。这可能会使应用程序遭受不同的攻击,如 CSRF 攻击或 SQL 注入。
3.2. The debug() Method
3.2.debug() 方法
Additionally, the debug() method enables logging of Spring Security internals to assist with debugging configuration or request failures. This could be helpful in diagnosing security rules without the need for a debugger.
此外,debug() 方法启用了 Spring Security 内部日志,以协助调试配置或请求故障。这有助于诊断安全规则,而无需调试器。
Let’s see an example code that uses the debug() method to debug security:
让我们来看一个使用 debug() 方法调试安全性的示例代码:
@Bean
WebSecurityCustomizer debugSecurity() {
return (web) -> web.debug(true);
}
Here, we invoke debug() on the WebSecurity instance and set it to true. This globally enables debug logging across all security filters.
在这里,我们在 WebSecurity 实例上调用 debug() 并将其设置为 true。这将全面启用所有安全过滤器的调试日志记录。
3.3. The httpFirewall() Method
3.3.httpFirewall() 方法
Also, the WebSecurity class provides the httpFirewall() method to configure a firewall for a Spring application. It helps to set rules to permit certain actions at the global level.
此外,WebSecurity 类还提供了 httpFirewall() 方法,用于为 Spring 应用程序配置 防火墙。它有助于在全局级别设置允许某些操作的规则。
Let’s use the httpFirewall() method to determine which HTTP methods should be allowed in our application:
让我们使用 httpFirewall() 方法来确定我们的应用程序应允许哪些 HTTP 方法:
@Bean
HttpFirewall allowHttpMethod() {
List<String> allowedMethods = new ArrayList<String>();
allowedMethods.add("GET");
allowedMethods.add("POST");
StrictHttpFirewall firewall = new StrictHttpFirewall();
firewall.setAllowedHttpMethods(allowedMethods);
return firewall;
}
@Bean
WebSecurityCustomizer fireWall() {
return (web) -> web.httpFirewall(allowHttpMethod());
}
In the code above, we expose the HttpFirewall bean to configure a firewall for HTTP methods. By default, the DELETE, GET, HEAD, OPTIONS, PATCH, POST, and PUT methods are allowed. However, in our example, we configure the application with only the GET and POST methods.
在上面的代码中,我们使用 HttpFirewall Bean 为 HTTP 方法配置防火墙。默认情况下,允许使用 DELETE、GET、HEAD、OPTIONS、PATCH、POST 和 PUT 方法。不过,在我们的示例中,我们只配置了 GET 和 POST 方法。
We create a StrictHttpFirewall object and invoke the setAllowedHttpMethods() method on it. The method accepts a list of allowed HTTP methods as an argument.
我们创建一个 StrictHttpFirewall 对象,并调用 setAllowedHttpMethods() 方法。该方法接受一个允许的 HTTP 方法列表作为参数。
Finally, we expose a WebSecurityCustomizer bean to configure the firewall globally by passing the allowHttpMethod() method to the httpFirewall() method. Any request that’s not GET or POST will return an HTTP error because of the firewall.
最后,我们公开了一个 WebSecurityCustomizer bean,通过将 allowHttpMethod() 方法传递给 httpFirewall() 方法来全局配置防火墙。由于防火墙的存在,任何非 GET 或 POST 的请求都将返回 HTTP 错误。
4. Key Differences
4.主要差异
Rather than conflicting, the HttpSecurity and WebSecurity configurations can work together to provide global and resource-specific security rules.
HttpSecurity 和 WebSecurity 配置不会相互冲突,而是可以共同提供全局和特定于资源的安全规则。
However, if similar security rules are configured in both, the WebSecurity configuration takes the highest precedence:
但是,如果在两个配置中都配置了类似的安全规则,WebSecurity 配置具有最高优先级:
@Bean
WebSecurityCustomizer ignoringCustomizer() {
return (web) -> web.ignoring().antMatchers("/admin/**");
}
// ...
http.authorizeHttpRequests((authorize) -> authorize.antMatchers("/admin/**").hasRole("ADMIN")
// ...
Here, we ignore the “/admin/**” path globally in the WebSecurity configuration but also configure access rules for “/admin/**” paths in HttpSecurity.
在这里,我们在 WebSecurity 配置中全局忽略了”/admin/**“路径,但也在 HttpSecurity 中配置了”/admin/**“路径的访问规则。
In this case, the WebSecurity ignoring() configurations will override the HttpSecurity authorization for “/admin/**“.
在这种情况下,WebSecurity ignoring() 配置将覆盖”/admin/**“的 HttpSecurity 授权。
Also, in the SecurityFilterChain, the WebSecurity configuration is the first to execute when building a filter chain. The HttpSecurity rules are evaluated next.
此外,在 SecurityFilterChain 中,WebSecurity 配置在构建过滤链时首先执行。接下来将评估 HttpSecurity 规则。
Here’s a table showing the key differences between HttpSecurity and WebSecurity classes:
下面的表格显示了 HttpSecurity 和 WebSecurity 类之间的主要区别:
Feature | WebSecurity | HttpSecurity |
Scope | Global default security rule | Resource-specific security rules |
Examples | Firewall configuration, path ignoring, debug mode | URL rules, Authorization, CORS, CSRF |
Configuration approach | Per-resource conditional configuration | Global reusable security configuration |
5. Conclusion
5.结论
In this article, we learned the key usage of HttpSecurity and WebSecurity with example codes. Also, we saw how HttpSecurity allows configuring security rules for specific resources, while WebSecurity sets global default rules.
在本文中,我们通过示例代码了解了 HttpSecurity 和 WebSecurity 的主要用法。此外,我们还了解了 HttpSecurity 如何为特定资源配置安全规则,而 WebSecurity 如何设置全局默认规则。
Using them together provides flexibility to secure a Spring application at both global and resource-specific levels.
将它们结合起来使用,可以灵活地在全局和特定资源层面确保 Spring 应用程序的安全。
As always, the complete code for the examples is available over on GitHub.
与往常一样,这些示例的完整代码可在 GitHub 上获取。