【2022-3-18更新】
- 文档结构目录;
- 更新笔记。
导包
<!-- spring security 包含下面两个注释掉的包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.security</groupId>-->
<!-- <artifactId>spring-security-web</artifactId>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.security</groupId>-->
<!-- <artifactId>spring-security-config</artifactId>-->
<!-- </dependency>-->
- WebSecurityConfigurerAdapter:自定义 Security 策略
- AuthenticationManagerBuilder:自定义认证策略
- @EnableWebSecurity:开启WebSecuryti模式
Authentication - 认证
Authorization - 授权
- Controller.java
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@RequestMapping("/toMain")
public String toLogin(){
return "redirect:main.html";
}
@RequestMapping("/toError")
public String Error(){
return "redirect:error.html";
}
}
本质上主要是使用了AOP 和 拦截器!
- SecurityConfiguration.java
package com.example.demo.config;
import com.example.demo.hanlder.MyAccessDeniedHandler;
import com.example.demo.hanlder.MyAuthenticationFailureHandler;
import com.example.demo.hanlder.MyAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private MyAccessDeniedHandler myAccessDeniedHandler;
// 下面自定义登录逻辑时需要用到
@Bean
public PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder();
<