当 Spring Boot 版本更新到 3 之后,最低要求的 JDK 版本变为 17,相应的 最新版本的 Spring Security 的配置也发生了变化,一下主要讲解一些新的 Spring Security 的配置方法
1. 配置由继承WebSeucrityConfigurerAdapter
变成只需添加一个SecurityFilterChain
的bean
即可。
- Remember Me Token Repository
@Bean
public PersistentTokenRepository tokenRepositoryByMemory() {return new InMemoryTokenRepositoryImpl();
}
- SecurityHandler 工具
public class SecurityHandler {public void onLoginSuccess(final HttpServletRequest request,final HttpServletResponse response,final Authentication authentication) {sendUtf8MessageToResponse(response, RespMessage.success("User " + authentication.getName() + " login success."));}public void onLoginFailure(final HttpServletRequest request,final HttpServletResponse response,final AuthenticationException exception) {log.error("Login failure, {}.", exception.getMessage());sendUtf8MessageToResponse(response, RespMessage.failure("Login failure: " + exception.getMessage()));}public void onAuthenticationFailure(final HttpServletRequest request,final HttpServletResponse response,final AuthenticationException exception) {log.error("Auth failure, {}.", exception.getMessage());sendUtf8MessageToResponse(response, RespMessage.failure(HttpStatus.UNAUTHORIZED, "Auth failure: " + exception.getMessage()));}public void onAccessDenied(final HttpServletRequest request,final HttpServletResponse response,final AccessDeniedException exception) {log.error("Access denied, {}.", exception.getMessage());sendUtf8MessageToResponse(response, RespMessage.failure(HttpStatus.FORBIDDEN, "Access denied: " + exception.getMessage()));}public void onLogoutSuccess(final HttpServletRequest request,final HttpServletResponse response,final Authentication authentication) {RespMessage<String> resp;if (Objects.nonNull(authentication)) {resp = RespMessage.success("Logout success: " + authentication.getName() + ".");} else {log.error("Logout failure: Unauthorized logout request.");resp = RespMessage.failure(HttpStatus.UNAUTHORIZED, "Unauthorized logout request.");}sendUtf8MessageToResponse(response, resp);}public CorsConfigurationSource configurationSource() {final CorsConfiguration corsConfiguration = new CorsConfiguration();corsConfiguration.addAllowedOriginPattern("*");corsConfiguration.setAllowCredentials(true);corsConfiguration.addAllowedHeader("*");corsConfiguration.addAllowedMethod("*");corsConfiguration.addExposedHeader("*");final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", corsConfiguration);return source;}private void sendUtf8MessageToResponse(final HttpServletResponse response,final RespMessage<?> respMessage) {response.setContentType(APPLICATION_JSON_VALUE);try {JSONUtil.toJsonStr(respMessage, response.getWriter());} catch (final IOException e) {log.error("Write To Response Failure: {}.", e.getMessage());}}
}
- UserDetailService
@Bean
public UserDetailsService userDetailsService() {final PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();final UserBuilder users = User.builder().passwordEncoder(encoder::encode);final InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();manager.createUser(users.username("user").password("password").roles("USER").build());manager.createUser(users.username("admin").password("password").roles("USER","ADMIN").build());return manager;
}
- Spring Srcurity 配置类
@Bean
public SecurityFilterChain filterChain(final HttpSecurity httpSecurity) throws Exception {// 解决 Json 数据返回中文乱码问题final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();encodingFilter.setEncoding(StandardCharsets.UTF_8.name());encodingFilter.setForceEncoding(true);return httpSecurity.addFilterBefore(encodingFilter, CsrfFilter.class).authorizeHttpRequests(auth -> auth.anyRequest().authenticated()).formLogin(formLogin -> formLogin.loginProcessingUrl("/auth/login").successHandler(securityHandler::onLoginSuccess).failureHandler(securityHandler::onLoginFailure).permitAll()).logout(logout -> logout.logoutUrl("/auth/logout").logoutSuccessHandler(securityHandler::onLogoutSuccess)).exceptionHandling(exception -> {exception.authenticationEntryPoint(securityHandler::onAuthenticationFailure);exception.accessDeniedHandler(securityHandler::onAccessDenied);}).cors(corsConfig -> corsConfig.configurationSource(securityHandler.configurationSource())).rememberMe(rememberMeConfig -> {rememberMeConfig.rememberMeParameter("remember");rememberMeConfig.userDetailsService(userDetailsService);rememberMeConfig.tokenRepository(tokenRepository);// 设置短一点的时间以测试 remember-me 的功能rememberMeConfig.tokenValiditySeconds(30);}).csrf(AbstractHttpConfigurer::disable).sessionManagement(AbstractHttpConfigurer::disable).build();
}
- TestController ebdpoint
@GetMapping("system-resource")
public RespMessage<String> getSystemResource() {log.info("Invoke system-resource api, get resource success.");return RespMessage.success("Congratulation get the system resource.");
}
2. login 请求测试,可以看到 remember-me cookie 成功返回,并且在下一次求中会携带该 token 去服务器端,在 cookie 的有效期内直接自动登录
3. 将 login 请求更改成以 Json 字符串的格式提交的形式
- RequestUtil 工具类
public final class RequestUtil {private RequestUtil() {}public static LoginRequest getLoginRequest(final HttpServletRequest request) {final ObjectMapper objectMapper = new ObjectMapper();try {return objectMapper.readValue(request.getInputStream(), LoginRequest.class);} catch (final Exception e) {log.error("Read LoginRequest Value Error: {}.", e.getMessage());throw new AuthenticationServiceException(e.getMessage());}}
}
- 自定义 UsernamePasswordAuthenticationFilter
public class JsonUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {@Overridepublic Authentication attemptAuthentication(final HttpServletRequest request,final HttpServletResponse response) throws AuthenticationException {if (!StrUtil.equalsIgnoreCase(HttpMethod.POST.name(), request.getMethod())|| !StrUtil.equalsIgnoreCase(APPLICATION_JSON_VALUE, request.getContentType())) {throw new AuthenticationServiceException("Authentication method or content type not supported: " + request.getMethod()+ ", " + request.getContentType());}final LoginRequest loginRequest = RequestUtil.getLoginRequest(request);final UsernamePasswordAuthenticationToken authRequest =new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());setDetails(request, authRequest);return getAuthenticationManager().authenticate(authRequest);}
}
- 添加自定义 UsernamePasswordAuthenticationFilter 到 IOC 容器中
private final SecurityHandler securityHandler;@Bean
public UsernamePasswordAuthenticationFilter usernamePasswordAuthenticationFilter() {final JsonUsernamePasswordAuthenticationFilter filter =new JsonUsernamePasswordAuthenticationFilter();filter.setFilterProcessesUrl("/auth/login");filter.setAuthenticationSuccessHandler(securityHandler::onLoginSuccess);filter.setAuthenticationFailureHandler(securityHandler::onLoginFailure);filter.setAuthenticationManager(authenticationManager());filter.setSecurityContextRepository(new HttpSessionSecurityContextRepository());return filter;
}
- 更改 Spring Security 配置类
// 将以下部分
.formLogin(formLogin -> formLogin.loginProcessingUrl("/auth/login").successHandler(securityHandler::onLoginSuccess).failureHandler(securityHandler::onLoginFailure).permitAll()
)
// 替换成以下部分即可
.formLogin(AbstractHttpConfigurer::disable)
.addFilterBefore(usernamePasswordAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
4. 发现问题:我们配置了开启了 SpringSecurity 的 remember 功能,为啥不生效了呢?
-
我们只是将 formLogin 给关闭了<
.formLogin(AbstractHttpConfigurer::disable)
>,使用了自定义的 Json 格式来获取用户名和密码等信息,并且携带了 remember 的信息过来。 -
如果我们保持这个自定义登录的配置不变,仅仅只加上
.formLogin(form -> {})
这一句话,其实 remember-me 功能已经解决了,虽然这可以解决问题,但这不是我们想要的,我们不就是需要自定义登录,把 formLogin 给关了吗? -
关闭了 formLogin 到底做了什么呢?就导致了 remember-me 不生效了呢,参数获取方式需要变了是一个原因,但还有其他的。
-
在源码 UsernamePasswordAuthenticationFilter 的 attemptAuthentication 方法断点查看变量发现如下:
-
使用 formLogin 配置的时候,rememberMeServices 是 PersistentTokenBaseRememberMeServices 实现的
-
使用 Json 格式自定义登录的时候,rememberMeServices 是 NullRememberMeServices 实现的
-
所以问题就出在这,当我们验证用户名密码之前,我们关闭了 formLogin 的话就没有正确配置好 rememberMeServices 的值
-
自定义 RememberMeServices
@Component public class CustomJsonRememberMeService extends PersistentTokenBasedRememberMeServices {private static final String REMEMBER_ME_ATTR_NAME = "remember";private static final Integer REMEMBER_ME_TOKEN_VALIDITY = 3600;public CustomJsonRememberMeService(final UserDetailsService userDetailsService,final PersistentTokenRepository tokenRepository) {super(UUID.randomUUID().toString(), userDetailsService, tokenRepository);setParameter(REMEMBER_ME_ATTR_NAME);setTokenValiditySeconds(REMEMBER_ME_TOKEN_VALIDITY);}@Overrideprotected boolean rememberMeRequested(final HttpServletRequest request, final String parameter) {final Object remember = request.getAttribute(REMEMBER_ME_ATTR_NAME);return Objects.nonNull(remember) && Boolean.parseBoolean(remember.toString());} }
- 修改 Security remember me 部分配置
// 只需要将以下部分 .rememberMe(rememberMeConfig -> {rememberMeConfig.rememberMeParameter("remember");rememberMeConfig.userDetailsService(userDetailsService);rememberMeConfig.tokenRepository(tokenRepository);rememberMeConfig.tokenValiditySeconds(30); })// 更改成以下部分即可,这里将 userDetailsService 和 tokenRepository 都移除了是因为 customJsonRememberMeService 已经定义好了这两个的实现了 private final RememberMeServices rememberMeServices; .rememberMe(rememberMeConfig -> rememberMeConfig.rememberMeServices(rememberMeServices))
- 修改 JsonUsernamePasswordAuthenticationFilter 部分
// 在获取 LoginRequest 对象之后,再从 LoginRequest 中获取 remember 的值并且存进 request 中以便 CustomJsonRememberMeService 中获取 final LoginRequest loginRequest = RequestUtil.getLoginRequest(request);// 以下是添加的代码 if (loginRequest.getRemember()) {request.setAttribute("remember", true); }
-
-
再使用 PostMan 调用接口已经生效了