1. The background

In this section we learn about Spring Security.

2. Knowledge

Spring Security is a framework that provides authentication, authorization, and protection against common attacks.

Spring Secrity handles authentication and authorization at the Web request level and method invocation level.

Spring Secrity implements authentication through filters, and DelegatingFilterProxy is a special Servlet filter that doesn’t do much work on its own. Simply delegate the work to a Javax.servlet.filter implementation class. .

Spring Security typically configures these:

  • Configuration of user storage (how to store user information)
  • Specify which requests require authentication and the expected permissions required
  • Customize the login page

Spring Security is flexible enough to do authentication based on a variety of user stores: memory, database, LDAP, custom, etc

Example 3.

1) Reference dependent libraries

<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring-security-version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId>  <artifactId>spring-security-config</artifactId> <version>${spring-security-version}</version> </dependency>Copy the code

Use the @enablewebsecurity annotation to EnableWebSecurity.

/** * @enablewebsecurity annotations will EnableWebSecurity. Spring Security must be configured in a bean that implements WebSecurityConfigurer, Or inherited WebSecurityConfigurerAdapter * / @ Configuration @ EnableWebSecurity public class MySecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); / / to enable memory data storage auth inMemoryAuthentication () passwordEncoder (passwordEncoder) .withUser("user").password(passwordEncoder.encode("123")).roles("USER").and() .withUser("admin").password(passwordEncoder.encode("admin")).roles("USER", "ADMIN"); } @override protected void configure(HttpSecurity HTTP) throws Exception {http.formlogin ()// Enable default login page.and () .authorizeRequests() // .antMatchers("/manage/**").authenticated() .antMatchers("/manage/**").hasRole("ADMIN") .anyRequest().permitAll(); }}Copy the code

The above code has two configuration methods:

  • Configure (AuthenticationManagerBuilder auth) : configure the memory storing user information, and increases the two accounts.
  • Configure (HttpSecurity HTTP) : authenticates requests.

My code is at: github.com/vir56k/java…

4.. Reference:

Docs. Spring. IO/spring – secu…