English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Spring Framework in Spring 3.1It has added Java configuration support. In Spring Security, Java configuration has been added to Spring Security 3.2In which we can configure Spring Security Without writing a single line of XML.
Here, we will create an example that implements Spring's security without using XML configuration. It includes the following steps.
The first step is to create a Spring Security Java configuration. Below is a simple basic Java configuration provided.
WebSecurityConfig.java
package com.w3codebox; import org.springframework.context.annotation.*; //import org.springframework.security.config.annotation.authentication.builders.*; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.*; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @EnableWebSecurity @ComponentScan("com.w3codebox") public class WebSecurityConfig implements WebMvcConfigurer { @Bean public UserDetailsService userDetailsService() throws Exception { InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); manager.createUser(User.withDefaultPasswordEncoder().username("w3codebox"). password("java123").roles("USER").build()); return manager; } protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/) .authorizeRequests() .anyRequest().hasRole("ADMIN") .and() .httpBasic(); } }
This configuration creates a configuration called springSecurityFilterChain for the Servlet filter. responsibleProtect the application URL, verify the submitted username and password, and redirect to the login form, etc.
The above Java configuration performs the following operations for our application.
to require authentication for each URL to create a login form to allow users to authenticate using form-based authentication to allow logout to prevent CSRF attacks such as security headers integration
Now, we will register it in the war file springSecurityFilterChain . To register, Spring Security provides the base class AbstractSecurityWebApplicationInitializer that we need to extend.
For a Spring MVC application, SecurityWebApplicationInitializer is as follows.
SecurityWebApplicationInitializer.java
package com.w3codebox; import org.springframework.security.web.context.*; public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { }
This code will register springSecurityFilterChain for each URL in our application.
Now, load WebSecurityConfig into our existing ApplicationInitializer and add it to the getRootConfigClasses() method.
MvcWebApplicationInitializer.java
package com.w3codebox; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class MvcWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] { WebSecurityConfig.class }; } @Override protected Class<?>[] getServletConfigClasses() { // TOdo Auto-generated method stub return null; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
WebSecurityConfigurerAdapter The class provides a configure(HttpSecurity http) method that contains the following default configuration. The default definition is as follows.
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .and() .httpBasic(); }
It is similar to the given XML.
<http <intercept-url pattern="/**" access="authenticated"/> <form-login /> <http-basic /> </http>
This method performs the following actions.
It ensures that each request made by the user requires authentication It allows users to authenticate using form-based login It allows users to authenticate using HTTP Basic authentication
Create a controller to handle user requests.
HomeController.java
package com.w3codebox.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class HomeController { @RequestMapping(value="/", method=RequestMethod.GET) public String index() { return "index"; } }
We have a view (.jsp) page index.jsp , which includes the following source code.
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Home Page</title> </head> <body> Welcome to the home page! </body> </html>
Our complete project is as follows.
Output:
We have only one action in the controller, which can only be accessed by genuine users. Therefore, when we run the application, it prompts us to enter login credentials. The output is given below.
This is The default login page provided by Spring SecurityPage, we did not create it. Although we can create our own login page and configure it with the application. We will do this in the next topic.
Now, provide login credentials to access the application resources. Spring Security verifies user credentials and ensures user authenticity.
Let's see what happens? If we enter incorrect credentials.
An event is triggered after clicking the login button. Bad Credentials (Incorrect credentials) error.
Now, using Correct credentials logged in./strong>
This credential matched and displayed the homepage (index.jsp).