欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring security 使用自定义AuthenticationFailureHandler无法跳转failureUrl

程序员文章站 2024-03-19 15:41:58
...

默认AuthenticationFailureHandler源码

  • org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer
protected final void updateAuthenticationDefaults() {
	if (loginProcessingUrl == null) {
		loginProcessingUrl(loginPage);
	}
	if (failureHandler == null) {
		// 默认使用/login?error
		failureUrl(loginPage + "?error");
	}

	final LogoutConfigurer<B> logoutConfigurer = getBuilder().getConfigurer(
			LogoutConfigurer.class);
	if (logoutConfigurer != null && !logoutConfigurer.isCustomLogoutSuccess()) {
		logoutConfigurer.logoutSuccessUrl(loginPage + "?logout");
	}
}
public final T failureUrl(String authenticationFailureUrl) {
	// 默认使用SimpleUrlAuthenticationFailureHandler
	T result = failureHandler(new SimpleUrlAuthenticationFailureHandler(
			authenticationFailureUrl));
	// 此处保存失败url
	this.failureUrl = authenticationFailureUrl;
	return result;
}
protected final void updateAccessDefaults(B http) {
	// 如果设置了permitAll,此处将设置保存的failureUrl为permitAll
	if (permitAll) {
		PermitAllSupport.permitAll(http, loginPage, loginProcessingUrl, failureUrl);
	}
}
  • org.springframework.security.config.annotation.web.configurers.PermitAllSupport
public static void permitAll(
	HttpSecurityBuilder<? extends HttpSecurityBuilder<?>> http, String... urls) {
	for (String url : urls) {
		if (url != null) {
			// 此处使用的是完全匹配规则,因此/login与/login?error需要两条匹配规则
			permitAll(http, new ExactUrlRequestMatcher(url));
		}
	}
}
private final static class ExactUrlRequestMatcher implements RequestMatcher {
	private String processUrl;

	private ExactUrlRequestMatcher(String processUrl) {
		this.processUrl = processUrl;
	}

	public boolean matches(HttpServletRequest request) {
		String uri = request.getRequestURI();
		String query = request.getQueryString();

		if (query != null) {
			uri += "?" + query;
		}
		// 必须uri与query完全匹配
		if ("".equals(request.getContextPath())) {
			return uri.equals(processUrl);
		}

		return uri.equals(request.getContextPath() + processUrl);
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("ExactUrl [processUrl='").append(processUrl).append("']");
		return sb.toString();
	}
}

使用自定义AuthenticationFailureHandler

  • org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer
public final T failureHandler(
		AuthenticationFailureHandler authenticationFailureHandler) {
	// 此处清空了保存的failureUrl
	this.failureUrl = null;
	this.failureHandler = authenticationFailureHandler;
	return getSelf();
}

总结

  1. 如果使用自定义AuthenticationFailureHandler继承SimpleUrlAuthenticationFailureHandler或进行类似的页面跳转,
    需在WebSecurityConfigurerAdapter中额外配置失败跳转url的访问控制规则
http.authorizeRequests().antMatchers("/login?error").permitAll()