Master Spring Security: A Hands‑On Guide to @EnableWebSecurity and HttpSecurity Configuration

This tutorial walks you through setting up a Spring Boot project with Spring Security, explains the @EnableWebSecurity annotation, shows how to extend WebSecurityConfigurerAdapter, demonstrates overriding configure(AuthenticationManagerBuilder) and configure(HttpSecurity) methods with concrete code examples, and provides a concise reference table of common HttpSecurity methods.

Programmer DD
Programmer DD
Programmer DD
Master Spring Security: A Hands‑On Guide to @EnableWebSecurity and HttpSecurity Configuration

Overview

The article demonstrates how to configure Spring Security in a Spring Boot application using a minimal example. It shows how to clone a sample repository, start the demo, and then explains the key annotations and classes needed for authentication and authorization.

Getting Started

Clone the repository https://github.com/ChinaSilence/any-spring-security.git and run the application with Maven: mvn spring-boot:run After the application starts, open http://localhost:8080 and log in with the credentials username: anoy and password: pwd.

@EnableWebSecurity

The @EnableWebSecurity annotation activates Spring Security’s web‑security support. When placed on a @Configuration class, it tells Spring to look for a WebSecurityConfigurer implementation—typically a subclass of WebSecurityConfigurerAdapter —to build the security filter chain.

WebSecurityConfigurerAdapter

Extending WebSecurityConfigurerAdapter provides a convenient base class for customizing security. The subclass is automatically registered as a WebSecurityConfigurer and can override specific methods to define authentication providers, user‑details services, and HTTP‑security rules.

Overriding configure methods

/**
 * Configure in‑memory authentication with a user and an admin.
 */
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
        .withUser("user").password("password").roles("USER").and()
        .withUser("admin").password("password").roles("USER", "ADMIN");
}

/**
 * Configure HTTP security: require authentication for any request,
 * enable form‑login and HTTP basic authentication.
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .anyRequest().authenticated()
        .and().formLogin()
        .and().httpBasic();
}

The first method creates an in‑memory UserDetailsService with two users. The second method builds the filter chain, enforcing authentication for every request and enabling both form‑based and basic authentication mechanisms.

Common HttpSecurity methods

openidLogin()

– configure OpenID‑based authentication. headers() – add security‑related HTTP headers to responses. cors() – configure Cross‑Origin Resource Sharing. sessionManagement() – customize session handling. csrf() – enable CSRF protection (enabled by default when using the adapter). logout() – configure logout handling; default URL is /logout. anonymous() – define representation for anonymous users (default role ROLE_ANONYMOUS). formLogin() – enable form‑based login; generates a default login page if none is supplied. oauth2Login() – configure OAuth 2.0 / OpenID Connect authentication. httpBasic() – enable HTTP Basic authentication. addFilterAt() – insert a custom filter at a specific position in the filter chain.

AuthenticationManagerBuilder

The AuthenticationManagerBuilder is a helper used to construct an AuthenticationManager. It simplifies the creation of in‑memory, LDAP, or JDBC authentication and the registration of custom UserDetailsService or AuthenticationProvider implementations.

AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(objectPostProcessor);
// Example: in‑memory authentication
builder.inMemoryAuthentication()
       .withUser("user").password("pwd").roles("USER");
AuthenticationManager manager = builder.build();
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentAuthenticationspring-securityHttpSecurity
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.