秒懂SpringBoot之全网最易懂的Spring Security教程
SpringBoot整合Spring-Security 认证篇(保姆级教程)
SpringBoot整合Spring Security【超详细教程】
spring security 超详细使用教程(接入springboot、前后端分离)

Security 自定义 UsernamePasswordAuthenticationFilter 替换原拦截器
SpringSecurity自定义UsernamePasswordAuthenticationFilter
自定义过滤器替换 UsernamePasswordAuthenticationFilter

Spring Security 实战干货:必须掌握的一些内置 Filter
Spring Security权限控制框架使用指南

你真的了解 Cookie 和 Session 吗?
Session 、Cookie和Token三者的关系和区别

简单使用 Spring Security

pom.xml

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--springSecurity--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>
</dependencies>

启动类

@SpringBootApplication
public class SpringBootSecurityApplication {public static void main(String[] args) {SpringApplication.run(SpringBootSecurityApplication.class, args);}
}

配置文件

server:port: 8001spring:security:user:name: adminpassword: 123456

controller

@RestController
@RequestMapping("/auth")
public class TestController {@GetMapping("/hello")public String sayHello(){return "hello security";}
}

启动项目
访问 http://localhost:8001/auth/hello 会出现登录页面
在这里插入图片描述

输入账号密码 正常输出

如果没有配置账号密码
username:user
password:随机生成,会打印在你的控制台日志上。

Spring Security 代码执行流程

一个请求过来Spring Security会按照下图的步骤处理:
在这里插入图片描述

进入到Filter中 UsernamePasswordAuthenticationFilter

在这里插入图片描述
进入 UsernamePasswordAuthenticationFilter

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) req;HttpServletResponse response = (HttpServletResponse) res;if (!requiresAuthentication(request, response)) {chain.doFilter(request, response);return;}if (logger.isDebugEnabled()) {logger.debug("Request is to process authentication");}Authentication authResult;try {authResult = attemptAuthentication(request, response);if (authResult == null) {return;}//此处底层会设置  JSESSIONID 并存储 JSESSIONIDsessionStrategy.onAuthentication(authResult, request, response);}catch (InternalAuthenticationServiceException failed) {//失败处理unsuccessfulAuthentication(request, response, failed);return;}catch (AuthenticationException failed) {//失败处理unsuccessfulAuthentication(request, response, failed);return;}// Authentication successif (continueChainBeforeSuccessfulAuthentication) {chain.doFilter(request, response);}//成功后处理successfulAuthentication(request, response, chain, authResult);
}
//UsernamePasswordAuthenticationFilter.java
public Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response) throws AuthenticationException {...String username = obtainUsername(request);String password = obtainPassword(request);...UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);...//this.getAuthenticationManager()  默认为 ProviderManagerreturn this.getAuthenticationManager().authenticate(authRequest);
}

进入 ProviderManager
循环执行 AuthenticationProvider 的 authenticate 方法

//ProviderManager.java
public Authentication authenticate(Authentication authentication)throws AuthenticationException {...for (AuthenticationProvider provider : getProviders()) {...result = provider.authenticate(authentication);if (result != null) {if (eraseCredentialsAfterAuthentication&& (result instanceof CredentialsContainer)) {...//此处会将密码设置为空((CredentialsContainer) result).eraseCredentials();}...return result;}...}...
}

默认执行 DaoAuthenticationProvider 的 authenticate

//AbstractUserDetailsAuthenticationProvider.java
public Authentication authenticate(Authentication authentication)throws AuthenticationException {...// Determine usernameString username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED": authentication.getName();...//获取用户信息user = retrieveUser(username,(UsernamePasswordAuthenticationToken) authentication);...try {//校验用户密码additionalAuthenticationChecks(user,(UsernamePasswordAuthenticationToken) authentication);}...return createSuccessAuthentication(principalToReturn, authentication, user);
}

SessionId 处理

sessionStrategy.onAuthentication 最终回执行到
//设置 Set-Cookie

// sessionStrategy.onAuthentication 最终回执行到 
//org.apache.catalina.connector.Request
public String changeSessionId() {Session session = this.getSessionInternal(false);if (session == null) {throw new IllegalStateException(sm.getString("coyoteRequest.changeSessionId"));}// StandardManagerManager manager = this.getContext().getManager();//获取新的 SessionIdString newSessionId = manager.rotateSessionId(session);//将 SessionId 设置到 response 中this.changeSessionId(newSessionId);return newSessionId;
}
  • 获取新 SessionId 并将 SessionId 存储
    manager.rotateSessionId 会生成新的 SessionId 并将 SessionId 存储到 StandardManager(父级 ManagerBase) 的
    protected Map<String, Session> sessions = new ConcurrentHashMap<>()
@Override
public String rotateSessionId(Session session) {String newId = generateSessionId();changeSessionId(session, newId, true, true);return newId;
}protected void changeSessionId(Session session, String newId,boolean notifySessionListeners, boolean notifyContainerListeners) {String oldId = session.getIdInternal();session.setId(newId, false);session.tellChangedSessionId(newId, oldId,notifySessionListeners, notifyContainerListeners);
}@Override
public void setId(String id, boolean notify) {if ((this.id != null) && (manager != null))manager.remove(this);this.id = id;if (manager != null)manager.add(this);if (notify) {tellNew();}
}@Override
public void add(Session session) {sessions.put(session.getIdInternal(), session);int size = getActiveSessions();if( size > maxActive ) {synchronized(maxActiveUpdateLock) {if( size > maxActive ) {maxActive = size;}}}
}
  • 重设 需要返回的 SessionId
public void changeSessionId(String newSessionId) {...if (response != null) {Cookie newCookie = ApplicationSessionCookieConfig.createSessionCookie(context,newSessionId, isSecure());response.addSessionCookieInternal(newCookie);}
}public void addSessionCookieInternal(final Cookie cookie) {if (isCommitted()) {return;}String name = cookie.getName();final String headername = "Set-Cookie";...if (!set) {addHeader(headername, header);}
}

登录时session 校验

通过断点可发现 最终回执行到 StandardManager(父级 ManagerBase) 的 findSession 中
刚好使用了 上面生成的 sessionId

//ManagerBase.java
@Override
public Session findSession(String id) throws IOException {if (id == null) {return null;}return sessions.get(id);
}

获取用户信息

//DaoAuthenticationProvider.java
protected final UserDetails retrieveUser(String username,UsernamePasswordAuthenticationToken authentication)throws AuthenticationException {...UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username);if (loadedUser == null) {throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");}return loadedUser;...
}

执行 getUserDetailsService(UserDetailsService) 获取 用户信息
默认执行到 InMemoryUserDetailsManager 中的 loadUserByUsername方法

// InMemoryUserDetailsManager.java
public UserDetails loadUserByUsername(String username)throws UsernameNotFoundException {UserDetails user = users.get(username.toLowerCase());if (user == null) {throw new UsernameNotFoundException(username);}return new User(user.getUsername(), user.getPassword(), user.isEnabled(),user.isAccountNonExpired(), user.isCredentialsNonExpired(),user.isAccountNonLocked(), user.getAuthorities());
}

校验用户密码是否正确

//DaoAuthenticationProvider.java
protected void additionalAuthenticationChecks(UserDetails userDetails,UsernamePasswordAuthenticationToken authentication)throws AuthenticationException {if (authentication.getCredentials() == null) {logger.debug("Authentication failed: no credentials provided");throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials","Bad credentials"));}String presentedPassword = authentication.getCredentials().toString();//判断密码是否正确if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {logger.debug("Authentication failed: password does not match stored value");throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials","Bad credentials"));}
}

根据以上执行流程 可针对相应步骤自定义内容

自定义配置相关步骤

自定义 UserDetailsService

默认是 InMemoryUserDetailsManager

@Service
public class UserDetailService implements UserDetailsService {@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();SysUser sysUser = new SysUser();sysUser.setUsername("admin");sysUser.setPassword(bCryptPasswordEncoder.encode("13579"));Map<String, SysUser> map = new HashMap<>();map.put(sysUser.getUsername(), sysUser);return map.get(username);}
}

用自定义的 UserDetailsService 时 需设置加密方式

@Bean
public BCryptPasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();
}

也可通过在 config 中配置对应的实现类

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//配置对应的权限相关对象}
}

自定义 AuthenticationProvider

默认是 DaoAuthenticationProvider

@Component
public class MyAuthenticationProvider implements AuthenticationProvider {@Autowiredprivate UserDetailService userDetailService;@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {String username = authentication.getName();String presentedPassword = (String) authentication.getCredentials();// 根据用户名获取用户信息UserDetails userDetails = this.userDetailService.loadUserByUsername(username);if (StringUtils.isEmpty(userDetails)) {throw new BadCredentialsException("用户名不存在");} else {//校验 将输入的密码presentedPassword加密  和 数据库中的密码userDetails.getPassword() 校验是否一致UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(userDetails, authentication.getCredentials(), userDetails.getAuthorities());result.setDetails(authentication.getDetails());return result;}}@Overridepublic boolean supports(Class<?> authentication) {return true;}
}

自定义 AuthenticationManager

默认是 ProviderManager

@Beanprotected AuthenticationManager authenticationManager() throws Exception {ProviderManager manager = new ProviderManager(Arrays.asList(myAuthenticationProvider));return manager;} 

自定义 Filter, 重写 UsernamePasswordAuthenticationFilter

public class LoginFilter extends UsernamePasswordAuthenticationFilter {private AuthenticationManager authenticationManager;public LoginFilter(AuthenticationManager authenticationManager) {this.authenticationManager = authenticationManager;}//这个方法是用来去尝试验证用户的@Overridepublic Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {try {String username = request.getParameter("username");String password = request.getParameter("password");return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));} catch (Exception e) {try {response.setContentType("application/json;charset=utf-8");response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);PrintWriter out = response.getWriter();Map<String, Object> map = new HashMap<>();map.put("code", HttpServletResponse.SC_UNAUTHORIZED);map.put("message", "账号或密码错误!");out.write(new ObjectMapper().writeValueAsString(map));out.flush();out.close();} catch (Exception e1) {e1.printStackTrace();}throw new RuntimeException(e);}}//成功之后执行的方法@Overridepublic void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {SysUser sysUser = new SysUser();sysUser.setUsername(authResult.getName());String token = JwtToolUtils.tokenCreate(authResult.getName(), 600);response.addHeader("Authorization", "RobodToken " + token);    //将Token信息返回给用户try {//登录成功时,返回json格式进行提示response.setContentType("application/json;charset=utf-8");response.setStatus(HttpServletResponse.SC_OK);PrintWriter out = response.getWriter();Map<String, Object> map = new HashMap<String, Object>(4);map.put("code", HttpServletResponse.SC_OK);map.put("message", "登陆成功!");out.write(new ObjectMapper().writeValueAsString(map));out.flush();out.close();} catch (Exception e1) {e1.printStackTrace();}//执行父级流程//super.successfulAuthentication(request, response, chain, authResult);}
}

自定义 Filter, 添加在 UsernamePasswordAuthenticationFilter 之前

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException, ServletException, IOException {//获取tokenString token = request.getHeader("token");if (!StringUtils.hasText(token)) {//token为空的话, 就不管它, 让SpringSecurity中的其他过滤器处理请求//请求放行filterChain.doFilter(request, response);return;}//jwt 解析token 后的用户信息SysUser securityUser = new SysUser();securityUser.setUsername("aa");securityUser.setPassword("123");//将用户安全信息存入SecurityContextHolder, 在之后SpringSecurity的过滤器就不会拦截UsernamePasswordAuthenticationToken authenticationToken =new UsernamePasswordAuthenticationToken(securityUser, null, null);SecurityContextHolder.getContext().setAuthentication(authenticationToken);//放行filterChain.doFilter(request, response);}
}

配置自定义的过滤器

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@AutowiredJwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;//配置SpringSecurity  Http 相关信息@Overridepublic void configure(HttpSecurity http) throws Exception {http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);}
}

项目启动相关初始化

Security 账号密码加载

UserDetailsServiceAutoConfiguration 加载时

获取 SecurityProperties 配置文件中配置的账号密码, 如果密码是默认的随机生成的,将密码输入到控制台

//UserDetailsServiceAutoConfiguration.java
@Bean
@ConditionalOnMissingBean(type = "org.springframework.security.oauth2.client.registration.ClientRegistrationRepository")
@Lazy
public InMemoryUserDetailsManager inMemoryUserDetailsManager(SecurityProperties properties,ObjectProvider<PasswordEncoder> passwordEncoder) {SecurityProperties.User user = properties.getUser();List<String> roles = user.getRoles();return new InMemoryUserDetailsManager(User.withUsername(user.getName()).password(getOrDeducePassword(user, passwordEncoder.getIfAvailable())).roles(StringUtils.toStringArray(roles)).build());
}private String getOrDeducePassword(SecurityProperties.User user, PasswordEncoder encoder) {String password = user.getPassword();//如果是默认动态生成的,输出到控制台if (user.isPasswordGenerated()) {logger.info(String.format("%n%nUsing generated security password: %s%n", user.getPassword()));}if (encoder != null || PASSWORD_ALGORITHM_PATTERN.matcher(password).matches()) {return password;}return NOOP_PASSWORD_PREFIX + password;
}

SecurityProperties.java
默认账号 user
默认密码随机生成
passwordGenerated 设置密码是否是随机生成的。 默认为true, 当配置的密码不为空时,置为false

public class SecurityProperties {...private User user = new User();...public static class User {private String name = "user";private String password = UUID.randomUUID().toString();private boolean passwordGenerated = true;...public void setPassword(String password) {if (!StringUtils.hasLength(password)) {return;}this.passwordGenerated = false;this.password = password;}...}
}

设置默认的用户账号信息(users)

public InMemoryUserDetailsManager(UserDetails... users) {for (UserDetails user : users) {createUser(user);}
}
public void createUser(UserDetails user) {Assert.isTrue(!userExists(user.getUsername()), "user should not exist");users.put(user.getUsername().toLowerCase(), new MutableUser(user));
}

在这里插入图片描述

WebSecurityConfiguration 加载

涉及到的Configuration

ReactiveUserDetailsServiceAutoConfiguration@AutoConfigureAfterRSocketMessagingAutoConfigurationSecurityAutoConfiguration#importSpringBootWebSecurityConfigurationWebSecurityEnablerConfiguration@EnableWebSecurity #importWebSecurityConfigurationSpringWebMvcImportSelectorOAuth2ImportSelector@EnableGlobalAuthenticationAuthenticationConfiguration@ImportObjectPostProcessorConfigurationSecurityDataConfigurationSecurityFilterAutoConfiguration	UserDetailsServiceAutoConfiguration

加载流程

当未配置自定义的 WebSecurityConfigurerAdapter@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(WebSecurityConfigurerAdapter.class)
@ConditionalOnMissingBean(WebSecurityConfigurerAdapter.class)
@ConditionalOnWebApplication(type = Type.SERVLET)
public class SpringBootWebSecurityConfiguration {@Configuration(proxyBeanMethods = false)@Order(SecurityProperties.BASIC_AUTH_ORDER)static class DefaultConfigurerAdapter extends WebSecurityConfigurerAdapter {}
}@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(AuthenticationManager.class)
@ConditionalOnBean(ObjectPostProcessor.class)
@ConditionalOnMissingBean(value = { AuthenticationManager.class, AuthenticationProvider.class, UserDetailsService.class },type = { "org.springframework.security.oauth2.jwt.JwtDecoder","org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector" })
public class UserDetailsServiceAutoConfiguration {private static final String NOOP_PASSWORD_PREFIX = "{noop}";private static final Pattern PASSWORD_ALGORITHM_PATTERN = Pattern.compile("^\\{.+}.*$");private static final Log logger = LogFactory.getLog(UserDetailsServiceAutoConfiguration.class);@Bean@ConditionalOnMissingBean(type = "org.springframework.security.oauth2.client.registration.ClientRegistrationRepository")@Lazypublic InMemoryUserDetailsManager inMemoryUserDetailsManager(SecurityProperties properties,ObjectProvider<PasswordEncoder> passwordEncoder) {SecurityProperties.User user = properties.getUser();List<String> roles = user.getRoles();return new InMemoryUserDetailsManager(User.withUsername(user.getName()).password(getOrDeducePassword(user, passwordEncoder.getIfAvailable())).roles(StringUtils.toStringArray(roles)).build());}private String getOrDeducePassword(SecurityProperties.User user, PasswordEncoder encoder) {String password = user.getPassword();if (user.isPasswordGenerated()) {logger.info(String.format("%n%nUsing generated security password: %s%n", user.getPassword()));}if (encoder != null || PASSWORD_ALGORITHM_PATTERN.matcher(password).matches()) {return password;}return NOOP_PASSWORD_PREFIX + password;}}@Configuration(proxyBeanMethods = false)
@Import(ObjectPostProcessorConfiguration.class)
public class AuthenticationConfiguration {@Autowired(required = false)public void setGlobalAuthenticationConfigurers(List<GlobalAuthenticationConfigurerAdapter> configurers) {configurers.sort(AnnotationAwareOrderComparator.INSTANCE);this.globalAuthConfigurers = configurers;}
}WebSecurityConfiguration 中的  setFilterChainProxySecurityConfigurer 加载会 获取所有 SecurityConfigurer 的实现类 对 获取到的 SecurityConfigurer 集合排序循环执行 webSecurity.apply(webSecurityConfigurer) 将 webSecurityConfigurer 添加到 webSecurity 的 configurers 中设置 this.webSecurityConfigurers = webSecurityConfigurers;@Configuration(proxyBeanMethods = false)
public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAware {@Autowired(required = false)public void setFilterChainProxySecurityConfigurer(ObjectPostProcessor<Object> objectPostProcessor,@Value("#{@autowiredWebSecurityConfigurersIgnoreParents.getWebSecurityConfigurers()}") List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers)throws Exception {webSecurity = objectPostProcessor.postProcess(new WebSecurity(objectPostProcessor));if (debugEnabled != null) {webSecurity.debug(debugEnabled);}webSecurityConfigurers.sort(AnnotationAwareOrderComparator.INSTANCE);Integer previousOrder = null;Object previousConfig = null;for (SecurityConfigurer<Filter, WebSecurity> config : webSecurityConfigurers) {Integer order = AnnotationAwareOrderComparator.lookupOrder(config);if (previousOrder != null && previousOrder.equals(order)) {throw new IllegalStateException("@Order on WebSecurityConfigurers must be unique. Order of "+ order + " was already used on " + previousConfig + ", so it cannot be used on "+ config + " too.");}previousOrder = order;previousConfig = config;}for (SecurityConfigurer<Filter, WebSecurity> webSecurityConfigurer : webSecurityConfigurers) {webSecurity.apply(webSecurityConfigurer);}this.webSecurityConfigurers = webSecurityConfigurers;}@Bean@DependsOn(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)public SecurityExpressionHandler<FilterInvocation> webSecurityExpressionHandler() {return webSecurity.getExpressionHandler();}@Bean(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)public Filter springSecurityFilterChain() throws Exception {boolean hasConfigurers = webSecurityConfigurers != null&& !webSecurityConfigurers.isEmpty();if (!hasConfigurers) {WebSecurityConfigurerAdapter adapter = objectObjectPostProcessor.postProcess(new WebSecurityConfigurerAdapter() {});webSecurity.apply(adapter);}return webSecurity.build();}
}WebSecurityConfiguration 中的 webSecurityExpressionHandler 加载 @DependsOn 依赖 springSecurityFilterChainWebSecurityConfiguration 中的 springSecurityFilterChain 加载1、判断是否有定义的 webSecurityConfigurers2、执行 webSecurity.build()执行到 AbstractSecurityBuilder 中的 build 方法执行到 AbstractConfiguredSecurityBuilder 中的 doBuild 方法@Overrideprotected final O doBuild() throws Exception {synchronized (configurers) {buildState = BuildState.INITIALIZING;beforeInit();init();buildState = BuildState.CONFIGURING;beforeConfigure();configure();buildState = BuildState.BUILDING;O result = performBuild();buildState = BuildState.BUILT;return result;}}整体执行流程1beforeInit();2init(); 循环执行 configurers 的 init 方法执行到 WebSecurityConfigurerAdapter 中的 init 方法public void init(final WebSecurity web) throws Exception {final HttpSecurity http = getHttp();web.addSecurityFilterChainBuilder(http).postBuildAction(() -> {FilterSecurityInterceptor securityInterceptor = http.getSharedObject(FilterSecurityInterceptor.class);web.securityInterceptor(securityInterceptor);});}protected final HttpSecurity getHttp() throws Exception {if (http != null) {return http;}AuthenticationEventPublisher eventPublisher = getAuthenticationEventPublisher();localConfigureAuthenticationBldr.authenticationEventPublisher(eventPublisher);AuthenticationManager authenticationManager = authenticationManager();authenticationBuilder.parentAuthenticationManager(authenticationManager);Map<Class<?>, Object> sharedObjects = createSharedObjects();http = new HttpSecurity(objectPostProcessor, authenticationBuilder,sharedObjects);...configure(http);return http;}authenticationManager(); 获取 AuthenticationManager protected AuthenticationManager authenticationManager() throws Exception {...authenticationManager = authenticationConfiguration.getAuthenticationManager();...}public AuthenticationManager getAuthenticationManager() throws Exception {...for (GlobalAuthenticationConfigurerAdapter config : globalAuthConfigurers) {authBuilder.apply(config);}authenticationManager = authBuilder.build();...}globalAuthConfigurers 获取 GlobalAuthenticationConfigurerAdapter 的实现类 //TODO 循环执行 authBuilder.apply(config)GlobalAuthenticationConfigurerAdapter 添加到 authBuilder 的 configurers 中authBuilder.build();public final O build() throws Exception {if (this.building.compareAndSet(false, true)) {this.object = doBuild();return this.object;}throw new AlreadyBuiltException("This object has already been built");}执行到 AbstractSecurityBuilder 中的 build 方法执行到 AbstractConfiguredSecurityBuilder 中的 doBuild 方法执行流程同上InitializeUserDetailsManagerConfigurerpublic void configure(AuthenticationManagerBuilder auth) throws Exception {if (auth.isConfigured()) {return;}UserDetailsService userDetailsService = getBeanOrNull(UserDetailsService.class);if (userDetailsService == null) {return;}PasswordEncoder passwordEncoder = getBeanOrNull(PasswordEncoder.class);UserDetailsPasswordService passwordManager = getBeanOrNull(UserDetailsPasswordService.class);DaoAuthenticationProvider provider = new DaoAuthenticationProvider();provider.setUserDetailsService(userDetailsService);if (passwordEncoder != null) {provider.setPasswordEncoder(passwordEncoder);}if (passwordManager != null) {provider.setUserDetailsPasswordService(passwordManager);}provider.afterPropertiesSet();auth.authenticationProvider(provider);}1、获取 UserDetailsService (InMemoryUserDetailsManager)2、获取 PasswordEncoder 为空3、获取 UserDetailsPasswordService (InMemoryUserDetailsManager)4DaoAuthenticationProvider provider = new DaoAuthenticationProvider();public DaoAuthenticationProvider() {setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());}public static PasswordEncoder createDelegatingPasswordEncoder() {String encodingId = "bcrypt";Map<String, PasswordEncoder> encoders = new HashMap<>();encoders.put(encodingId, new BCryptPasswordEncoder());encoders.put("ldap", new org.springframework.security.crypto.password.LdapShaPasswordEncoder());encoders.put("MD4", new org.springframework.security.crypto.password.Md4PasswordEncoder());encoders.put("MD5", new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("MD5"));encoders.put("noop", org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance());encoders.put("pbkdf2", new Pbkdf2PasswordEncoder());encoders.put("scrypt", new SCryptPasswordEncoder());encoders.put("SHA-1", new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-1"));encoders.put("SHA-256", new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-256"));encoders.put("sha256", new org.springframework.security.crypto.password.StandardPasswordEncoder());encoders.put("argon2", new Argon2PasswordEncoder());return new DelegatingPasswordEncoder(encodingId, encoders);}设置加密方式5、设置对应的 UserDetailsServicePasswordEncoderUserDetailsPasswordService6、执行 afterPropertiesSet7、auth.authenticationProvider 往 AuthenticationManagerBuilder 的 authenticationProviders 中添加数据会执行到 AuthenticationManagerBuilder@Overrideprotected ProviderManager performBuild() throws Exception {if (!isConfigured()) {logger.debug("No authenticationProviders and no parentAuthenticationManager defined. Returning null.");return null;}ProviderManager providerManager = new ProviderManager(authenticationProviders,parentAuthenticationManager);if (eraseCredentials != null) {providerManager.setEraseCredentialsAfterAuthentication(eraseCredentials);}if (eventPublisher != null) {providerManager.setAuthenticationEventPublisher(eventPublisher);}providerManager = postProcess(providerManager);return providerManager;}为 http 的 configurers 添加对应的 configurerconfigure(http);protected void configure(HttpSecurity http) throws Exception {logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();}public FormLoginConfigurer<HttpSecurity> formLogin() throws Exception {return getOrApply(new FormLoginConfigurer<>());}public FormLoginConfigurer() {super(new UsernamePasswordAuthenticationFilter(), null);usernameParameter("username");passwordParameter("password");}// 调用 login 接口才会进入 UsernamePasswordAuthenticationFilter过滤器public UsernamePasswordAuthenticationFilter() {super(new AntPathRequestMatcher("/login", "POST"));}protected AbstractAuthenticationFilterConfigurer(F authenticationFilter,String defaultLoginProcessingUrl) {this();this.authFilter = authenticationFilter;if (defaultLoginProcessingUrl != null) {loginProcessingUrl(defaultLoginProcessingUrl);}}addSecurityFilterChainBuilder(http)//为 WebSecurity 的 securityFilterChainBuilders 中添加数据public WebSecurity addSecurityFilterChainBuilder(SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder) {this.securityFilterChainBuilders.add(securityFilterChainBuilder);return this;}3beforeConfigure();4configure(); 循环执行 configurers 的 configure 方法执行 自定义的 configure 方法5performBuild();@Overrideprotected Filter performBuild() throws Exception {...for (SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder : securityFilterChainBuilders) {securityFilterChains.add(securityFilterChainBuilder.build());}...Filter result = filterChainProxy;postBuildAction.run();return result;}此时的 securityFilterChainBuilders 是 HttpSecuritysecurityFilterChainBuilder.build()循环执行 securityFilterChainBuilder 中的 configurers执行 FormLoginConfigurer 的 configure 方法 // AbstractAuthenticationFilterConfigurer.class@Overridepublic void configure(B http) throws Exception {PortMapper portMapper = http.getSharedObject(PortMapper.class);if (portMapper != null) {authenticationEntryPoint.setPortMapper(portMapper);}RequestCache requestCache = http.getSharedObject(RequestCache.class);if (requestCache != null) {this.defaultSuccessHandler.setRequestCache(requestCache);}authFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));authFilter.setAuthenticationSuccessHandler(successHandler);authFilter.setAuthenticationFailureHandler(failureHandler);if (authenticationDetailsSource != null) {authFilter.setAuthenticationDetailsSource(authenticationDetailsSource);}SessionAuthenticationStrategy sessionAuthenticationStrategy = http.getSharedObject(SessionAuthenticationStrategy.class);if (sessionAuthenticationStrategy != null) {authFilter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy);}RememberMeServices rememberMeServices = http.getSharedObject(RememberMeServices.class);if (rememberMeServices != null) {authFilter.setRememberMeServices(rememberMeServices);}F filter = postProcess(authFilter);http.addFilter(filter);}//authFilter 为 UsernamePasswordAuthenticationFilter.java将 filter 添加到 HttpSecurity 中, 在过滤器中使用

过滤器链

FilterComparator() {Step order = new Step(INITIAL_ORDER, ORDER_STEP);put(ChannelProcessingFilter.class, order.next());put(ConcurrentSessionFilter.class, order.next());put(WebAsyncManagerIntegrationFilter.class, order.next());put(SecurityContextPersistenceFilter.class, order.next());put(HeaderWriterFilter.class, order.next());put(CorsFilter.class, order.next());put(CsrfFilter.class, order.next());put(LogoutFilter.class, order.next());filterToOrder.put("org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter",order.next());filterToOrder.put("org.springframework.security.saml2.provider.service.servlet.filter.Saml2WebSsoAuthenticationRequestFilter",order.next());put(X509AuthenticationFilter.class, order.next());put(AbstractPreAuthenticatedProcessingFilter.class, order.next());filterToOrder.put("org.springframework.security.cas.web.CasAuthenticationFilter",order.next());filterToOrder.put("org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter",order.next());filterToOrder.put("org.springframework.security.saml2.provider.service.servlet.filter.Saml2WebSsoAuthenticationFilter",order.next());put(UsernamePasswordAuthenticationFilter.class, order.next());put(ConcurrentSessionFilter.class, order.next());filterToOrder.put("org.springframework.security.openid.OpenIDAuthenticationFilter", order.next());put(DefaultLoginPageGeneratingFilter.class, order.next());put(DefaultLogoutPageGeneratingFilter.class, order.next());put(ConcurrentSessionFilter.class, order.next());put(DigestAuthenticationFilter.class, order.next());filterToOrder.put("org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter", order.next());put(BasicAuthenticationFilter.class, order.next());put(RequestCacheAwareFilter.class, order.next());put(SecurityContextHolderAwareRequestFilter.class, order.next());put(JaasApiIntegrationFilter.class, order.next());put(RememberMeAuthenticationFilter.class, order.next());put(AnonymousAuthenticationFilter.class, order.next());filterToOrder.put("org.springframework.security.oauth2.client.web.OAuth2AuthorizationCodeGrantFilter",order.next());put(SessionManagementFilter.class, order.next());put(ExceptionTranslationFilter.class, order.next());put(FilterSecurityInterceptor.class, order.next());put(SwitchUserFilter.class, order.next());}

异常问题处理过程

1、通过 postman 访问登录接口异常

未配置自定义的 WebSecurityConfigurerAdapter 时
通过 postman 访问页面登录的接口, 获取 JSESSIONID 失败

curl --location 'http://localhost:8001/login' \
--header 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Cookie: JSESSIONID=24E4E66AD4D606C8F98022A30ABD49F9' \
--data-urlencode 'username=admin' \
--data-urlencode 'password=2'

是因为 CsrfFilter 中 doFilterInternal 有个 !csrfToken.getToken().equals(actualToken) 导致获取失败

protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response, FilterChain filterChain)throws ServletException, IOException {request.setAttribute(HttpServletResponse.class.getName(), response);CsrfToken csrfToken = this.tokenRepository.loadToken(request);...if (!csrfToken.getToken().equals(actualToken)) {...}filterChain.doFilter(request, response);
}

处理方式

  • 1、需要在 headers 中增加 X-CSRF-TOKEN 参数
    在这里插入图片描述

  • 2、禁用 csrf
    参照 WebSecurityConfigurerAdapter 的配置 增加 禁用 csrf

@Override
protected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/diannao/81085.shtml
繁体地址,请注明出处:http://hk.pswp.cn/diannao/81085.shtml
英文地址,请注明出处:http://en.pswp.cn/diannao/81085.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

LeetCode 3392.统计符合条件长度为 3 的子数组数目:一次遍历模拟

【LetMeFly】3392.统计符合条件长度为 3 的子数组数目&#xff1a;一次遍历模拟 力扣题目链接&#xff1a;https://leetcode.cn/problems/count-subarrays-of-length-three-with-a-condition/ 给你一个整数数组 nums &#xff0c;请你返回长度为 3 的 子数组&#xff0c;满足…

读论文笔记-CoOp:对CLIP的handcrafted改进

读论文笔记-Learning to Prompt for Vision-Language Models Problems 现有基于prompt engineering的多模态模型在设计合适的prompt时有很大困难&#xff0c;从而设计了一种更简单的方法来制作prompt。 Motivations prompt engineering虽然促进了视觉表示的学习&#xff0c…

从零构建 MCP Server 与 Client:打造你的第一个 AI 工具集成应用

目录 &#x1f680; 从零构建 MCP Server 与 Client&#xff1a;打造你的第一个 AI 工具集成应用 &#x1f9f1; 1. 准备工作 &#x1f6e0;️ 2. 构建 MCP Server&#xff08;服务端&#xff09; 2.1 初始化服务器 &#x1f9e9; 3. 添加自定义工具&#xff08;Tools&…

Django 自定义celery-beat调度器,查询自定义表的Cron表达式进行任务调度

学习目标&#xff1a; 通过自定义的CronScheduler调度器在兼容标准的调度器的情况下&#xff0c;查询自定义任务表去生成调度任务并分配给celery worker进行执行 不了解Celery框架的小伙伴可以先看一下我的上一篇文章&#xff1a;Celery框架组件分析及使用 学习内容&#xff…

蓝桥杯 1. 确定字符串是否包含唯一字符

确定字符串是否包含唯一字符 原题目链接 题目描述 实现一个算法来识别一个字符串的字符是否是唯一的&#xff08;忽略字母大小写&#xff09;。 若唯一&#xff0c;则输出 YES&#xff0c;否则输出 NO。 输入描述 输入一行字符串&#xff0c;长度不超过 100。 输出描述 输…

a-upload组件实现文件的上传——.pdf,.ppt,.pptx,.doc,.docx,.xls,.xlsx,.txt

实现下面的上传/下载/删除功能&#xff1a;要求支持&#xff1a;【.pdf,.ppt,.pptx,.doc,.docx,.xls,.xlsx,.txt】 分析上面的效果图&#xff0c;分为【上传】按钮和【文件列表】功能&#xff1a; 解决步骤1&#xff1a;上传按钮 直接上代码&#xff1a; <a-uploadmultip…

.NET Core 数据库ORM框架用法简述

.NET Core ORM框架用法简述 一、主流.NET Core ORM框架概述 在.NET Core生态系统中&#xff0c;主流的ORM(Object-Relational Mapping)框架包括&#xff1a; ​​Entity Framework Core (EF Core)​​ - 微软官方推出的ORM框架​​Dapper​​ - 轻量级微ORM​​Npgsql.Entit…

halcon打开图形窗口

1、dev_open_window 参数如下&#xff1a; 1&#xff09;Row(输入参数) y方向上&#xff0c;图形窗口距离左上角顶端的像素个数 2&#xff09;Column(输入参数) x方向上&#xff0c;距离左上角左边的像素个数 3&#xff09;Width(输入参数) 图形窗口宽度 4&#xff09;He…

2025东三省D题深圳杯D题数学建模挑战赛数模思路代码文章教学

完整内容请看文章最下面的推广群 一、问题一&#xff1a;混合STR图谱中贡献者人数判定 问题解析 给定混合STR图谱&#xff0c;识别其中的真实贡献者人数是后续基因型分离与个体识别的前提。图谱中每个位点最多应出现2n个峰&#xff08;n为人数&#xff09;&#xff0c;但由…

iView Table 组件跨页选择功能实现文档

iView Table 组件跨页选择功能实现文档 功能概述 实现基于 iView Table 组件的多选功能&#xff0c;支持以下特性&#xff1a; ✅ 跨页数据持久化选择✅ 当前页全选/取消全选✅ 自动同步选中状态显示✅ 分页切换状态保持✅ 高性能大数据量支持 实现方案 技术栈 iView UI 4…

家庭服务器IPV6搭建无限邮箱系统指南

qq邮箱操作 // 邮箱配置信息 // 注意&#xff1a;使用QQ邮箱需要先开启IMAP服务并获取授权码 // 设置方法&#xff1a;登录QQ邮箱 -> 设置 -> 账户 -> 开启IMAP/SMTP服务 -> 生成授权码 服务器操作 fetchmail 同步QQ邮箱 nginx搭建web显示本地同步过来的邮箱 ssh…

Tauri v1 与 v2 配置对比

本文档对比 Tauri v1 和 v2 版本的配置结构和内容差异&#xff0c;帮助开发者了解版本变更并进行迁移。 配置结构变化 v1 配置结构 {"package": { ... },"tauri": { "allowlist": { ... },"bundle": { ... },"security":…

对js的Date二次封装,继承了原Date的所有方法,增加了自己扩展的方法,可以实现任意时间往前往后推算多少小时、多少天、多少周、多少月;

封装js时间工具 概述 该方法继承了 js 中 Date的所有方法&#xff1b;同时扩展了一部分自用方法&#xff1a; 1、任意时间 往前推多少小时&#xff0c;天&#xff0c;月&#xff0c;周&#xff1b;参数1、2必填&#xff0c;参数3可选beforeDate(num,formatter,dateVal); befo…

TimeDistill:通过跨架构蒸馏的MLP高效长期时间序列预测

原文地址&#xff1a;https://arxiv.org/abs/2502.15016 发表会议&#xff1a;暂定&#xff08;但是Star很高&#xff09; 代码地址&#xff1a;无 作者&#xff1a;Juntong Ni &#xff08;倪浚桐&#xff09;, Zewen Liu &#xff08;刘泽文&#xff09;, Shiyu Wang&…

DeepSeek最新大模型发布-DeepSeek-Prover-V2-671B

2025 年 4 月 30 日&#xff0c;DeepSeek 开源了新模型 DeepSeek-Prover-V2-671B&#xff0c;该模型聚焦数学定理证明任务&#xff0c;基于混合专家架构&#xff0c;使用 Lean 4 框架进行形式化推理训练&#xff0c;参数规模达 6710 亿&#xff0c;结合强化学习与大规模合成数据…

如何用AI生成假期旅行照?

以下是2025年最新AI生成假期旅行照片的实用工具推荐及使用指南&#xff0c;结合工具特点、研发背景和适用场景进行综合解析&#xff1a; 一、主流AI旅行照片生成工具推荐与对比 1. 搜狐简单AI&#xff08;国内工具&#xff09; • 特点&#xff1a; • 一键优化与背景替换&…

ElaticSearch

ElaticSearch: 全文搜索 超级强&#xff0c;比如模糊查询、关键词高亮等 海量数据 高效查询&#xff0c;比传统关系数据库快得多&#xff08;尤其是搜索&#xff09; 灵活的数据结构&#xff08;Schema灵活&#xff0c;可以动态字段&#xff09; 分布式高可用&#xff0c;天…

Android开发,实现一个简约又好看的登录页

文章目录 1. 编写布局文件2.设计要点说明3. 效果图4. 关于作者其它项目视频教程介绍 1. 编写布局文件 编写activity.login.xml 布局文件 <?xml version"1.0" encoding"utf-8"?> <androidx.appcompat.widget.LinearLayoutCompat xmlns:android…

机器学习:【抛掷硬币的贝叶斯后验概率】

首先,抛硬币的问题通常涉及先验概率、似然函数和后验概率。假设用户可能想通过观察一系列的正面(H)和反面(T)来更新硬币的偏差概率。例如,先验可能假设硬币是均匀的,但随着观察到更多数据,用贝叶斯定理计算后验分布。 通常,硬币的偏差可以用Beta分布作为先验,因为它…

Echarts 问题:自定义的 legend 点击后消失,格式化 legend 的隐藏文本样式

文章目录 问题分析实现步骤代码解释问题 如下图所示,在自定义的 legend 点击后会消失 分析 我把隐藏的图例字体颜色设为灰色,可以借助 legend.formatter 和 legend.textStyle 结合 option.series 的 show 属性来达成。以下是具体的实现步骤和示例代码: <!DOCTYPE ht…