Personal blog address :http://alexaccele.github.io/
springboot Want to use spring security The module needs to import corresponding dependencies
stay pom Add some code to the file
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Then write a simple configuration class SecurityConfiger This configuration class needs to inherit WebSecurityConfigurerAdapter This abstract class
/* Security configuration class */
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)// Enable method security
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
And mark it @EnableWebSecurity annotation , Open this comment
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({WebSecurityConfiguration.class, SpringWebMvcImportSelector.class})
@EnableGlobalAuthentication
@Configuration
public @interface EnableWebSecurity {
boolean debug() default false;
}
You can see that it contains @Configuration Annotated , Indicates that this is a configuration class
Then we need to reload configure Methods to achieve the results we want
Method | describe |
configure(WebSecurity webSecurity) | By overloading , To configure SpringSecurity Of Filter chain |
configure(HttpSecurity http) | By overloading , Configure how to protect requests through interceptors |
configure(AuthenticationManagerBuilder auth) | By overloading , To configure userdetail service |
All of the above methods need not be overloaded , It only needs to be overloaded according to specific requirements , Here’s an example of overloading :
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/css/**","/fonts/**","/js/**","/index").permitAll()// Allow access to static files
.antMatchers("/admins/**").hasRole("ADMIN")// You have a role to access
.and()
.formLogin()// be based on form Form login validation Go to /login page
.loginPage("/login").failureUrl("/login-error")// Customize login interface and failure interface
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()// Authentication information is stored in memory
.withUser("root").password("123456").roles("ADMIN");
}
That’s all springboot Integrate spring security A simple configuration class of , It is configured to access static files , Permission settings for some specific pages , And login authentication , The login page , Login failed configuration ; And configuration for the production environment , take User Information is stored in memory