介绍:SpringSecurity是基于Filter和AOP来对Spring应用进行保护的一套框架,它可对请求级别和方法级别进行安全保护。
模块一:对请求地址进行保护:
I 开启安全认证
- 引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- SpringSecurity依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- 热部署、测试 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
- 启动程序,访问某URL
- 在页面输入认证账号
默认账号为: user
默认密码会在控制台打印 “Using generated security password: f6ce299d-c5bc-4719-8762-02fa1c133ade”
- 请求成功
II自定义表单的本地内存认证
- 继承类WebSecurityConfigurerAdapter并实现相关方法
package com.dedu.config; import org.springframework.context.annotation.Bean; 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; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login", "/authentication/form").permitAll() //自定义不进行认证的页面 .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") // 自定义登录页面 .loginProcessingUrl("/authentication/form")// 自定义登录路径,即页面需要post的路径 .successForwardUrl("/index") //配置登陆成功后的页面 .failureUrl("/login") .and() .logout() .logoutSuccessUrl("/login") //配置退出后的页面 .permitAll() .and() .csrf().disable();// 禁用跨站攻击 } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("dedu").password(new BCryptPasswordEncoder().encode("dedu")).roles("ADMIN"); } @Override public void configure(WebSecurity web) throws Exception { //指定忽略的静态资源 web.ignoring().antMatchers("/global/**"); } /** * 必须显示定义加密编码器 * @return */ @Bean