- 任何Spring Web应用本质上只是一个Servlet;
- Security Filter在Http请求到达Controller之前过滤每一个传入的Http请求;
| 过滤器名称 | 作用 |
|---|---|
| BasicAuthenticationFilter | 如果在请求中找到一个Basic Auth Http头,如果找到,则尝试用该头中的用户名和密码验证用户 |
| UsernamePasswordAuthenticationFilter | 若在请求参数或者Post的RequestBody中找到用户名和密码,则尝试用这些值对用户进行身份验证 |
| DefaultLoginPageGeneratingFiltler | 默认登录页面生成过滤器,用于生成一个登录页面,若没有明确禁用这个功能,那么就会生成一个登录页面。这就是为什么在启用SpringSecurity时候,会得到一个默认的页面的原因 |
| DefaultLogoutPageGeneratingFilter | 若没有禁用该功能,则会生成一个注销页面 |
| FilterSecurityInterceptor | 过滤安全拦截器,用于授权逻辑 |
依赖类库 安全配置org.webjars webjars-locator-core org.webjars bootstrap ${bootstrap.version} org.springframework.boot spring-boot-starter-thymeleaf
SecurityConfig
package com.vleus.uaa.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
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;
@EnableWebSecurity(debug = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.httpBasic(Customizer.withDefaults())
.formLogin(form -> form.loginPage("/login"))
.authorizeRequests(req -> req.antMatchers("/api
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().mvcMatchers("/public
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webjars
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login")
.setViewName("login");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
}
CSRF攻击和保护
防止收到CSRF攻击的方式
CSRF Token
在响应设置Cookie的SameSite属性
Remember me功能
- 为解决session过期后用户的直接访问问题;
- Spring Security提供开箱即用的配置 rememberMe;
- 原理:使用Cookie存储用户名,过期时间,以及一个Hash;
Hash:md5(用户名+过期时间+密码+key)
登录成功和失败后的处理- 登录成功后的处理:AuthenticationSuccessHandler;
- 登录失败后的处理:AuthenticationFailureHandler;
- 退出登录成功后的处理:LogoutSuccessHandler;



