Home  >  Spring 5

Spring @EnableWebSecurity Example

By Arvind Rai, December 02, 2019
The Spring Security @EnableWebSecurity annotation is annotated at class level with @Configuration annotation to enable web securities in our application defined by WebSecurityConfigurer implementations. The WebSecurityConfigurerAdapter is the implementation class of WebSecurityConfigurer interface. The @EnableWebSecurity enables the web securities defined by WebSecurityConfigurerAdapter automatically. To override web securities defined by WebSecurityConfigurerAdapter in our Java configuration class, we need to extend this class and override its methods.


Technologies Used

Find the technologies being used in our example.
1. Java 11
2. Spring 5.2.1.RELEASE
3. Spring Boot 2.2.1.RELEASE
4. Tomcat 9
5. Maven 3.5.2

Maven Dependencies

Find the Maven dependencies.
pom.xml
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.2.1.RELEASE</version>
	<relativePath />
</parent>
<properties>
	<context.path>spring-app</context.path>
	<java.version>11</java.version>
</properties>
<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-security</artifactId>
	</dependency>
</dependencies> 

Using @EnableWebSecurity

Find the code to use @EnableWebSecurity in our application.
SecurityConfig.java
package com.concretepage.config;
import org.springframework.context.annotation.Configuration;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
		   .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
		   .antMatchers("/user/**").access("hasRole('ROLE_USER')")
		   .and().formLogin();
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/resources/**");
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication().withUser("ram").password("{noop}ram123").roles("ADMIN");
		auth.inMemoryAuthentication().withUser("ravan").password("{noop}ravan123").roles("USER");
	}
} 
To enable Spring Security debug, use debug attribute.
@EnableWebSecurity(debug = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  ------
} 

Now find the JavaConfig to enable Spring MVC used in our demo application.
AppConfig.java
package com.concretepage.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan("com.concretepage")
@EnableWebMvc
public class AppConfig {
} 

WebSecurityConfigurerAdapter

The WebSecurityConfigurerAdapter is the implementation class of WebSecurityConfigurer interface. The WebSecurityConfigurerAdapter is extended by Spring Security Java configuration to override default web security. We can override following methods of WebSecurityConfigurerAdapter class.
configure(HttpSecurity http): Configures HttpSecurity , for example, authorizing requests and role access.
configure(WebSecurity web): Configures WebSecurity, for example, we can ignore certain requests (eg. loading JS file) to be authenticated.
configure(AuthenticationManagerBuilder auth): Configures AuthenticationManager.
authenticationManagerBean(): Exposes AuthenticationManager as bean.
userDetailsServiceBean(): Exposes UserDetailsService as bean.

AbstractSecurityWebApplicationInitializer

We need to register DelegatingFilterProxy in our Spring Security application to use the springSecurityFilterChain before any other registered Filter. The AbstractSecurityWebApplicationInitializer is used to register DelegatingFilterProxy. We need to create a class as following.
SecurityInitializer.java
package com.concretepage.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
 
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
} 

Find the web application initializer class to register a DispatcherServlet used in our demo application.
WebAppInitializer.java
package com.concretepage.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { AppConfig.class };
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return null;
	}

	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}
} 

Controller

Find the controller class.
AppController.java
package com.concretepage.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AppController {
	@RequestMapping("/admin")
	public @ResponseBody String helloAdmin() {
		return "Welcome to Admin.";
	}
	
	@RequestMapping("/user")
	public @ResponseBody String helloUser() {
		return "Welcome to User.";
	}
} 

Output

Build and deploy the project and access the URL.
http://localhost:8080/spring-app/admin 
We will see Spring Security login page.
Spring @EnableWebSecurity Example
Login using credentials ram/ram123 and we will see welcome page.

References

Spring doc: @EnableWebSecurity
Spring Security Reference

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us