SpringSecurity过滤器之ExceptionTranslationFilter

ExceptionTranslationFilter是处理AuthenticationException(身份认证异常)和AccessDeniedException(权限异常)。ExceptionTranslationFilter用法和源码分析参考一文搞定 Spring Security 异常处理机制!

 

AuthenticationEntryPoint是处理AuthenticationException,默认实现是LoginUrlAuthenticationEntryPoint。

LoginUrlAuthenticationEntryPoint#commence(HttpServletRequest request, HttpServletResponse response,AuthenticationException authException):

public void commence(HttpServletRequest request, HttpServletResponse response,
		AuthenticationException authException) throws IOException, ServletException {
	if (!this.useForward) {
		// redirect to login page. Use https if forceHttps true
		String redirectUrl = buildRedirectUrlToLoginPage(request, response, authException);
		this.redirectStrategy.sendRedirect(request, response, redirectUrl);
		return;
	}
	String redirectUrl = null;
	if (this.forceHttps && "http".equals(request.getScheme())) {
		// First redirect the current request to HTTPS. When that request is received,
		// the forward to the login page will be used.
		redirectUrl = buildHttpsRedirectUrlForRequest(request);
	}
	if (redirectUrl != null) {
		this.redirectStrategy.sendRedirect(request, response, redirectUrl);
		return;
	}
	String loginForm = determineUrlToUseForThisRequest(request, response, authException);
	logger.debug(LogMessage.format("Server side forward to: %s", loginForm));
	RequestDispatcher dispatcher = request.getRequestDispatcher(loginForm);
	dispatcher.forward(request, response);
	return;
}

默认重定向到登录页面。

 
 
 

AccessDeniedHandler是处理AccessDeniedException异常。默认实现是AccessDeniedHandlerImpl。

AccessDeniedHandlerImpl#handle(HttpServletRequest request, HttpServletResponse response,AccessDeniedException accessDeniedException)

public void handle(HttpServletRequest request, HttpServletResponse response,
		AccessDeniedException accessDeniedException) throws IOException, ServletException {
	if (response.isCommitted()) {
		logger.trace("Did not write to response since already committed");
		return;
	}
	if (this.errorPage == null) {
		logger.debug("Responding with 403 status code");
		response.sendError(HttpStatus.FORBIDDEN.value(), HttpStatus.FORBIDDEN.getReasonPhrase());
		return;
	}
	// Put exception into request scope (perhaps of use to a view)
	request.setAttribute(WebAttributes.ACCESS_DENIED_403, accessDeniedException);
	// Set the 403 status code.
	response.setStatus(HttpStatus.FORBIDDEN.value());
	// forward to error page.
	if (logger.isDebugEnabled()) {
		logger.debug(LogMessage.format("Forwarding to %s with status code 403", this.errorPage));
	}
	request.getRequestDispatcher(this.errorPage).forward(request, response);
}

默认是返回403。

posted @ 2023-04-22 15:28  shigp1  阅读(221)  评论(0)    收藏  举报