Learning from Spring Security practice: creating a simple Spring Security Project

Reference course: Mr. Chen Muxin's "Spring Security practice" ...
Create spring boot project
maven reference
Declare controller
Run spring security demo application
Modify login information
WebSecurityConfigurerAdapter
Custom form landing page
Other form configuration items

Reference course: Mr. Chen Muxin's "Spring Security practice"

Create spring boot project

There are many ways to create a Spring Boot project through the Intellij IDEA. The easiest way is to use the Spring Initializr
Tools.
Spring Initializr allows us to select some common project dependencies in advance. Here, we choose Security as the construction of spring
The minimum dependency of Security project, select Web as the core dependency of Spring Boot to build Web application.

Next :

Next:

Create a directory structure for the project:

maven reference

In the auto built Spring Security project, spring initializer introduces the following dependencies for us:

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

We can see from the opening of spring boot starter security that it contains the following dependencies:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.3.1.RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <scope>compile</scope> </dependency>

Among them, spring security web and spring security config are two core modules, which are the minimum dependency of spring security recommended by the government.

Declare controller

Declare a test route TestController in the project:

package com.haan.springsecuritydemo; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @GetMapping public String hello(){ return "Hello Spring Security!"; } }

Run spring security demo application

Run the spring security demo application, start port 8080 by default, open the browser, and visit localhost:8080 , we found that the page had jumped to localhost:8080/login :

After the introduction of Spring Security project, although there is no relevant configuration or coding, Spring Security has a default running state, which requires that the corresponding URL resources can be accessed only after basic form authentication. The default user name is user, and the password is a string of random codes generated dynamically and printed to the console. To view the print information of the console:

After entering the user name and password, click the login button to access successfully:

Modify login information

In basic form authentication, user name and password can be configured. The most common is to modify them in the application configuration file under resources

spring.security.user.name=user02 spring.security.user.password=aaaaaa

Restart the program and find that the console no longer prints the default password string. At this time, use our custom user name and password to log in.

WebSecurityConfigurerAdapter

protected void configure(HttpSecurity http) throws Exception { this.logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity)."); ((HttpSecurity)((HttpSecurity)((AuthorizedUrl)http.authorizeRequests().anyRequest()).authenticated().and()).formLogin().and()).httpBasic(); }

You can see that the WebSecurityConfigurerAdapter has declared some security features by default:

  • Verify all requests.
  • Allow users to authenticate using form login (Spring Security provides a simple form login page).
  • Allows users to use HTTP basic authentication.

spring boot defines DefaultConfigurerAdapter by default. According to @ ConditionalOnMissingBean, when no other WebSecurityConfigurerAdapter is defined, DefaultConfigurerAdapter will be used:

@Configuration( proxyBeanMethods = false ) @ConditionalOnClass() @ConditionalOnMissingBean() @ConditionalOnWebApplication( type = Type.SERVLET ) public class SpringBootWebSecurityConfiguration { public SpringBootWebSecurityConfiguration() { } @Configuration( proxyBeanMethods = false ) @Order(2147483642) static class DefaultConfigurerAdapter extends WebSecurityConfigurerAdapter { DefaultConfigurerAdapter() { } } }

Custom form landing page

Spring boot provides the default implementation of WebSecurityConfigurerAdapter, which can provide basic form login authentication.

Although the automatically generated form login page can be started easily and quickly, most applications prefer to provide their own form login page. At this time, we need to provide our own WebSecurityConfigurerAdapter instead of DefaultConfigurerAdapter, and override the configuration method of WebSecurityConfigurerAdapter:

@EnableWebSecurity public class MyWebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/myLogin.html") //Indicate login page .permitAll() //Indicates that the login page allows all access .and() .csrf().disable(); } }
  • The authorizeRequests() method actually returns a URL interceptor registrar. We can call the anyRequest(), antMatchers(), regexMatchers() and other methods provided by it to match the system URL and specify the security policy for it.
  • The formLogin() method and httpBasic() method both declare the form authentication mode that Spring Security provides, and return the corresponding configurator respectively. Where formLogin(). loginPage ("/ myLogin.html ") specify a custom login

Page/ myLogin.html At the same time, Spring Security will use/ myLogin.html Register a POST route to receive login requests.

  • The csrf () method is the Cross Site Request Forgery protection function provided by spring security. When we inherit the WebSecurityConfigurer Adapter, the csrf () method will be turned on by default.

visit localhost:8080 , we found that the page jumped to localhost:8080/myLogin.html , because there is no myLogin.html File, so a 404 white page is prompted:

We create the page in the resources/static folder myLogin.html :

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello Security!</title> </head> <body> <h3>Landing page</h3> <form action="/myLogin.html" method="post"> <input type="text" name="username"> <br/> <input type="text" name="password"> <br/> <input type="submit" value="login"> </form> </body> </html>

Restart service, visit again localhost:8080 :

Enter the above application.properties The user's login account and password configured in login succeeded:

Other form configuration items

Specify login processing URL

After the form login page is customized, the URL to process the login request will change accordingly. By default,
If only loginPage is configured and loginProcessingUrl is not configured, then loginProcessingUrl is loginPage by default. If you need to customize the URL of login request, you need to configure loginProcessingUrl:

Restart the login, we found that the intermediate access localhost:8080/myLogin

Add: loginPage and loginProcessingUrl

  • Neither is configured: the default is / login
  • Configure both: according to your own
  • Configure loginProcessingUrl only: loginPage default / login
  • Configure loginPage only: loginprocessingurl is loginPage by default

Set login processed successfully

At this time, some readers may have questions, because according to the Convention, after sending the login request and successfully authenticating, the page will jump back to the original access page. In some systems, it's true to jump back to the original access page, but in some systems where the front and back ends are completely separated and all interactions are completed only by JSON, a section of JSON data will be returned during login to inform the front end whether the login is successful or not, and the front end will decide where to go
Manage the follow-up logic, instead of the server actively executing the page Jump. This can also be implemented in Spring Security.

The form login configuration module provides two methods, successHandler () and failureHandler (), which deal with the logic of login success and login failure respectively.

  • The successHandler () method has an Authentication parameter, which carries information such as the current login user name and its role;
  • The failureHandler () method takes an AuthenticationException exception parameter. The specific processing method needs to be customized according to the system situation.
@EnableWebSecurity public class MyWebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/myLogin.html") //Indicate login page .loginProcessingUrl("/myLogin") //Indicates the URL path to process the login, i.e. login form submission request .successHandler(new AuthenticationSuccessHandler() { // Set up successful login processor @Override public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { PrintWriter responseWriter = httpServletResponse.getWriter(); String name = authentication.getName(); responseWriter.write(name+" login success!"); } }) .failureHandler(new AuthenticationFailureHandler() { // Set up the failed login processor @Override public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { PrintWriter responseWriter = httpServletResponse.getWriter(); responseWriter.write("login error!"); } }) .permitAll() //Indicates that the login page allows all access .and() .csrf().disable(); } }

Correct account password:

Wrong account password:

23 June 2020, 22:44 | Views: 4793

Add new comment

For adding a comment, please log in
or create account

0 comments