privatevoidhandleAuthenticationException(HttpServletRequest request,HttpServletResponse response,FilterChain chain,AuthenticationException exception)throwsServletException,IOException{this.logger.trace("Sending to authentication entry point since authentication failed", exception);sendStartAuthentication(request, response, chain, exception);}/**
* 处理认证异常
*/protectedvoidsendStartAuthentication(HttpServletRequest request,HttpServletResponse response,FilterChain chain,AuthenticationException reason)throwsServletException,IOException{//清除存储在线程级别的上下文策略的认证信息,HttpSession级别的会在SecurityContextPersistenceFilter的finally代码块中被更新//因为现有的认证不再被认为有效SecurityContext context =SecurityContextHolder.createEmptyContext();SecurityContextHolder.setContext(context);//将当前的请求放入请求缓存器//这样当重新登录后,还能将请求包装为这一次请求this.requestCache.saveRequest(request, response);//执行认证异常处理器this.authenticationEntryPoint.commence(request, response, reason);}
2.2 handleAccessDeniedException(…)
privatevoidhandleAccessDeniedException(HttpServletRequest request,HttpServletResponse response,FilterChain chain,AccessDeniedException exception)throwsServletException,IOException{Authentication authentication =SecurityContextHolder.getContext().getAuthentication();boolean isAnonymous =this.authenticationTrustResolver.isAnonymous(authentication);//当是匿名用户和记住我用户if(isAnonymous ||this.authenticationTrustResolver.isRememberMe(authentication)){if(logger.isTraceEnabled()){
logger.trace(LogMessage.format("Sending %s to authentication entry point since access is denied",
authentication), exception);}//还是当成一个认证异常处理//表示需要完整登录(用用户名和密码登录)sendStartAuthentication(request, response, chain,newInsufficientAuthenticationException(this.messages.getMessage("ExceptionTranslationFilter.insufficientAuthentication","Full authentication is required to access this resource")));}else{if(logger.isTraceEnabled()){
logger.trace(LogMessage.format("Sending %s to access denied handler since access is denied", authentication),
exception);}//调用访问被拒绝处理器,进行处理this.accessDeniedHandler.handle(request, response, exception);}}