1.SessionManagementFilter 会话管理器
见名知意,会话管理器。主要是管理SecurityContext到会话中去。
主要内容:
1.防止重复执行
2.sessionAuthenticationStrategy session认证处理策略
sessionAuthenticationStrategy主要是用于在非匿名身份认证时,可以自定义策略去对HttpSession进行相关操作。
典型用途是确保会话存在或更改会话 ID 以防止会话固定攻击ChangeSessionIdAuthenticationStrategy和SessionFixationProtectionStrategy。
3.如果SecurityContext或者Authentication不存在
在这种情况下,将request中的session进行失效。
2.ExceptionTranslationFilter Spring Security异常处理器
这个主要是针对过Spring Security滤器链出现问题时,如何进行异常处理。在默认拦截器链中,主要是针对FilterSecurityInterceptor进行异常捕获。
如何处理SpringSecurity异常呢?
handleSpringSecurityException方法解析:
private void handleSpringSecurityException(HttpServletRequest request,
HttpServletResponse response, FilterChain chain, RuntimeException exception)
throws IOException, ServletException {
if (exception instanceof AuthenticationException) {
logger.debug(
"Authentication exception occurred; redirecting to authentication entry point",
exception);
// 清空SecurityContext中的Authentication
// requestCache中缓存当前request
// 转发或者重定向到登录
sendStartAuthentication(request, response, chain,
(AuthenticationException) exception);
}
else if (exception instanceof AccessDeniedException) {
// 当异常为访问被拒时
// 1.清空Authentication
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authenticationTrustResolver.isAnonymous(authentication) || authenticationTrustResolver.isRememberMe(authentication)) {
logger.debug(
"Access is denied (user is " + (authenticationTrustResolver.isAnonymous(authentication) ? "anonymous" : "not fully authenticated") + "); redirecting to authentication entry point",
exception);
// 转发或者重定向到登录
sendStartAuthentication(
request,
response,
chain,
new InsufficientAuthenticationException(
messages.getMessage(
"ExceptionTranslationFilter.insufficientAuthentication",
"Full authentication is required to access this resource")));
}
else {
logger.debug(
"Access is denied (user is not anonymous); delegating to AccessDeniedHandler",
exception);
// accessDeniedHandler 见过很多次了。就是到forbidden页面,或者error页面
accessDeniedHandler.handle(request, response,
(AccessDeniedException) exception);
}
}
}
sendStartAuthentication 转发或者重定向到认证入口
accessDeniedHandler.handle 转发到error页面或者返回403 forbidden
3.小结
这篇看了一下关于Session的管理和异常处理。
关于SessionManagementFilter这边,我们可以通过SessionManagementConfigurer来知道如何配置
SessionManagementFilter。
这里简单列一下可以配置的内容:
- SecurityContextRepository SecurityContext存储
- getSessionAuthenticationStrategy 配置Session处理策略
- sessionAuthenticationErrorUrl session认证失败跳转url
- getInvalidSessionStrategy Session失效策略
- getSessionAuthenticationFailureHandler session认证失败处理器
- isConcurrentSessionControlEnabled 并发session控制器
而异常处理这边我们也可以自定义AccessDeniedHandler,自定义AuthenticationEntryPoint。