Spring @EnableWebSecurity – Web Security Java Config Example

Java configuration example to enable spring security with the help of @EnableWebSecurity annotation and WebSecurityConfigurerAdapter class. This example is built on top of the spring webmvc hibernate integration example.

1. Maven

Start with including spring security jars. We are using maven so added respective dependencies in pom.xml.

<properties>
    <spring.version>5.0.7.RELEASE</spring.version>
</properties> 
 
<!-- Spring Security Core -->
<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-core</artifactId>
  <version>${spring.version}</version>
</dependency>
 
<!-- Spring Security Config -->
<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-config</artifactId>
  <version>${spring.version}</version>
</dependency>
 
<!-- Spring Security Web -->
<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-web</artifactId>
  <version>${spring.version}</version>
</dependency>

In case you are using Spring Boot, we can include the following dependency.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2. @EnableWebSecurity Configuration

We have created this simple security configuration and added two demo users ‘user‘ and ‘admin‘.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
 
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 
  @Autowired
  PasswordEncoder passwordEncoder;
 
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
    .passwordEncoder(passwordEncoder)
    .withUser("user").password(passwordEncoder.encode("123456")).roles("USER")
    .and()
    .withUser("admin").password(passwordEncoder.encode("123456")).roles("USER", "ADMIN");
  }
 
  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }
 
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
    .antMatchers("/login").permitAll()
    .antMatchers("/admin/**").hasRole("ADMIN")
    .antMatchers("/**").hasAnyRole("ADMIN", "USER")
    .and().formLogin()
    .and().logout().logoutSuccessUrl("/login").permitAll()
    .and().csrf().disable();
  }
}

3. Initializing Spring Security

In Spring, security is implemented using DelegatingFilterProxy. To register it, with spring container in Java configuration, you shall use AbstractSecurityWebApplicationInitializer.

The spring will detect the instance of this class during application startup, and register the DelegatingFilterProxy to use the springSecurityFilterChain before any other registered Filter. It also registers a ContextLoaderListener.

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
  //no code needed
}

Also, include SecurityConfig to AppInitializer.

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
 
   @Override
   protected Class<?>[] getRootConfigClasses() {
      return new Class[] { HibernateConfig.class, SecurityConfig.class };
   }
 
   @Override
   protected Class<?>[] getServletConfigClasses() {
      return new Class[] { WebMvcConfig.class };
   }
 
   @Override
   protected String[] getServletMappings() {
      return new String[] { "/" };
   }
}

4. Verifying Security

Start the application and launch the home page. You will be given a login page. It means spring security is configured and working correctly.

Login Form
Login Form

Login with username/password – ‘user’ and ‘123456’

Login Success
Login Success

Happy Learning !!

Sourcecode Download

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial