Spring Security
HttpSecurity
WebSecurity
AuthenticationManagerBuilder
Java Authentication

HttpSecurity, WebSecurity and AuthenticationManagerBuilder

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Securing web applications is a fundamental aspect of software development, particularly when dealing with sensitive data. Spring Security is one of the most robust frameworks for implementing authentication, authorization, and other security features in Java applications. Within Spring Security, HttpSecurity, WebSecurity, and AuthenticationManagerBuilder are key classes/interfaces that provide developers with tools for defining security configurations. This article explores these components in detail, providing technical explanations and examples.

HttpSecurity

HttpSecurity is a crucial part of configuring web-based security for specific HTTP requests. It allows developers to define which endpoints are secured and who can access them, leveraging a fluent API to set up configurations.

Core Features

  • URL-Based Authorization: Determines access based on URL patterns.
  • Form Login: Configurations related to login forms, managing login URL, success, and failure handlers.
  • Logout Options: Configuring logout behavior.
  • CSRF Protection: Cross-site request forgery protection.
  • Session Management: Manages session creation, concurrency, and rules.

Example

java
1@Configuration
2@EnableWebSecurity
3public class SecurityConfig extends WebSecurityConfigurerAdapter {
4    @Override
5    protected void configure(HttpSecurity http) throws Exception {
6        http
7            .authorizeRequests()
8                .antMatchers("/admin/**").hasRole("ADMIN")
9                .antMatchers("/", "/home").permitAll()
10                .anyRequest().authenticated()
11            .and()
12            .formLogin()
13                .loginPage("/login")
14                .permitAll()
15            .and()
16            .logout()
17                .permitAll();
18    }
19}

In this example, any request to /admin/** requires the user to have an ADMIN role, while access to / and /home is open to all users.

WebSecurity

While HttpSecurity focuses on securing specific HTTP requests, WebSecurity provides a mechanism to configure global settings affecting all requests. It is generally used to set paths that should be completely ignored by Spring Security, bypassing its filters.

Core Features

  • Security Filter Chain: Custom configuration of how requests are handled by Spring Security filters.
  • Ignoring Requests: Define paths that should be excluded from security constraints.

Example

java
1@Override
2public void configure(WebSecurity web) throws Exception {
3    web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
4}

In this example, static resources like CSS, JavaScript, and images are excluded from security filtering, allowing public access.

AuthenticationManagerBuilder

AuthenticationManagerBuilder is used for in-memory, JDBC, or LDAP-based authentication. It configures global authentication details for the application.

Core Features

  • In-Memory Authentication: Simplest way of managing static list of users, often used for testing purposes.
  • JDBC Authentication: Retrieves user details from a database.
  • LDAP Authentication: Integrates with external LDAP servers for user data.

Example

java
1@Override
2protected void configure(AuthenticationManagerBuilder auth) throws Exception {
3    auth
4        .inMemoryAuthentication()
5        .withUser("user").password("{noop}password").roles("USER")
6        .and()
7        .withUser("admin").password("{noop}admin").roles("ADMIN");
8}

In this example, two users are defined in-memory: a regular user and an administrator, each with their respective roles.

Comparison Table

ComponentPurposeKey FeaturesCommon Use Cases
HttpSecuritySecure specific HTTP requestsURL-based authorization, form login, CSRF protection, session managementConfiguring page-specific access and authentication
WebSecurityGlobal configurations for all requestsSecurity filter chain, ignoring requestsExcluding static resources from security filtering
AuthenticationManagerBuilderSet up authentication globallyIn-memory, JDBC, LDAP authenticationDefining global authentication strategies

Summary

Understanding the roles of HttpSecurity, WebSecurity, and AuthenticationManagerBuilder is crucial for effectively using Spring Security. Each component plays a specific role in defining the security landscape of an application. By setting up appropriate configurations for each, developers can ensure robust security and smooth authentication and authorization processes across their applications.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.