1. Overview
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.
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.
2. HttpSecurity
The HttpSecurity class helps to configure security for specific HTTP requests.
Also, it permits using the requestMatcher() method to restrict security configuration to a specific HTTP endpoint.
Furthermore, it provides flexibility to configure authorization for a specific HTTP request. We can create a role-based authentication with the hasRole() method.
Here’s an example code that uses the HttpSecurity class to restrict access to “/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.
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:
// ...
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.
Additionally, the HttpSecurity class helps with configuring CORS and CSRF protection in Spring Security.
3. WebSecurity
The WebSecurity class helps to configure security at a global level in a Spring application. We can customize WebSecurity by exposing the WebSecurityCustomizer bean.
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.
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.
3.1. The ignoring() Method
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.
Here’s an example that uses the ignoring() method to ignore static resources in a Spring application:
@Bean
WebSecurityCustomizer ignoringCustomizer() {
return (web) -> web.ignoring().requestMatchers("/resources/**", "/static/**");
}
Here, we use the ignoring() method to bypass static resources from a security check.
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.
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.
3.2. The debug() Method
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.
Let’s see an example code that uses the debug() method to debug security:
@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.
3.3. The httpFirewall() Method
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.
Let’s use the httpFirewall() method to determine which HTTP methods should be allowed in our application:
@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.
We create a StrictHttpFirewall object and invoke the setAllowedHttpMethods() method on it. The method accepts a list of allowed HTTP methods as an argument.
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.
4. Key Differences
Rather than conflicting, the HttpSecurity and WebSecurity configurations can work together to provide global and resource-specific security rules.
However, if similar security rules are configured in both, the WebSecurity configuration takes the highest precedence:
@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.
In this case, the WebSecurity ignoring() configurations will override the HttpSecurity authorization for “/admin/**“.
Also, in the SecurityFilterChain, the WebSecurity configuration is the first to execute when building a filter chain. The HttpSecurity rules are evaluated next.
Here’s a table showing the key differences between HttpSecurity and WebSecurity classes:
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
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.
Using them together provides flexibility to secure a Spring application at both global and resource-specific levels.
As always, the complete code for the examples is available over on GitHub.