表单登录

Spring Security 支持通过 HTML 表单提供用户名和密码。 本节详细介绍了基于表单的身份验证在 Spring Security 中的工作原理。spring-doc.cadn.net.cn

本节探讨基于表单的登录在 Spring Security 中的工作原理。 首先,我们来看用户是如何被重定向到登录表单的:spring-doc.cadn.net.cn

loginurlauthenticationentrypoint
图1. 重定向到登录页面

上图基于我们的 SecurityFilterChain 图构建。spring-doc.cadn.net.cn

number 1首先,用户向资源发送未经身份验证的请求 (/private) 对于其未获授权的情况。spring-doc.cadn.net.cn

number 2Spring Security 的AuthorizationFilter表示未认证的请求是拒绝访问通过抛出AccessDeniedException.spring-doc.cadn.net.cn

number 3由于用户未通过身份验证,ExceptionTranslationFilter启动开始身份验证并将重定向发送到配置好的登录页面AuthenticationEntryPoint. 在大多数情况下,AuthenticationEntryPointLoginUrlAuthenticationEntryPoint.spring-doc.cadn.net.cn

number 4浏览器请求其被重定向到的登录页面。spring-doc.cadn.net.cn

number 5应用程序中的某些内容,必须渲染登录页面.spring-doc.cadn.net.cn

当用户名和密码被提交时,UsernamePasswordAuthenticationFilter 会从 UsernamePasswordAuthenticationToken 实例中提取用户名和密码,并创建一个 https://docs.spring.io/spring-security/reference/servlet/authentication/architecture.html#servlet-authentication-authentication,该对象属于一种 Authentication 类型。 UsernamePasswordAuthenticationFilter 继承自 AbstractAuthenticationProcessingFilter,因此下图看起来应该非常相似:spring-doc.cadn.net.cn

usernamepasswordauthenticationfilter
图2. 用户名和密码认证

该图基于我们的 SecurityFilterChain 图表构建。spring-doc.cadn.net.cn

number 1当用户提交用户名和密码时,UsernamePasswordAuthenticationFilter创建UsernamePasswordAuthenticationToken,这是一种类型的Authentication,通过提取用户名和密码从HttpServletRequest实例。spring-doc.cadn.net.cn

number 2接下来,UsernamePasswordAuthenticationToken被传递到AuthenticationManager待认证的实例。 关于内容的详细信息AuthenticationManager看起来取决于用户信息已存储.spring-doc.cadn.net.cn

number 3如果身份验证失败,则失败.spring-doc.cadn.net.cn

  1. SecurityContextHolder 已被清空。spring-doc.cadn.net.cn

  2. RememberMeServices.loginFail 被调用。 如果未配置“记住我”功能,此操作将无效果。 请参阅 Javadoc 中的 RememberMeServices 接口。spring-doc.cadn.net.cn

  3. AuthenticationFailureHandler 被调用。 请参阅 Javadoc 中的 AuthenticationFailureHandlerspring-doc.cadn.net.cn

number 4如果认证成功,则成功.spring-doc.cadn.net.cn

  1. SessionAuthenticationStrategy 会收到新登录的通知。 请参阅 Javadoc 中的 SessionAuthenticationStrategy 接口。spring-doc.cadn.net.cn

  2. 认证已设置在 SecurityContextHolder 上。 请参阅 Javadoc 中的 SecurityContextPersistenceFilter 类。spring-doc.cadn.net.cn

  3. RememberMeServices.loginSuccess 被调用。 如果未配置“记住我”功能,此操作将无效果。 请参阅 Javadoc 中的 RememberMeServices 接口。spring-doc.cadn.net.cn

  4. ApplicationEventPublisher 发布一个 InteractiveAuthenticationSuccessEventspring-doc.cadn.net.cn

  5. AuthenticationSuccessHandler 被调用。通常,这是一个 SimpleUrlAuthenticationSuccessHandler,它会重定向到由 ExceptionTranslationFilter 在重定向到登录页面时保存的请求。spring-doc.cadn.net.cn

默认情况下,Spring Security 的表单登录是启用的。 然而,一旦提供了任何基于 Servlet 的配置,就必须显式地配置基于表单的登录。 以下示例展示了一个最小化的显式 Java 配置:spring-doc.cadn.net.cn

表单登录
public SecurityFilterChain filterChain(HttpSecurity http) {
	http
		.formLogin(withDefaults());
	// ...
}
<http>
	<!-- ... -->
	<form-login />
</http>
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
	http {
		formLogin { }
	}
	// ...
}

在上述配置中,Spring Security 会渲染一个默认的登录页面。 大多数生产应用程序都需要自定义登录表单。spring-doc.cadn.net.cn

以下配置演示了如何提供自定义登录表单。spring-doc.cadn.net.cn

自定义登录表单配置
public SecurityFilterChain filterChain(HttpSecurity http) {
	http
		.formLogin((form) -> form
			.loginPage("/login")
			.permitAll()
		);
	// ...
}
<http>
	<!-- ... -->
	<intercept-url pattern="/login" access="permitAll" />
	<form-login login-page="/login" />
</http>
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
	http {
		formLogin {
			loginPage = "/login"
			permitAll()
		}
	}
	// ...
}

当在 Spring Security 配置中指定了登录页面时,您需要负责渲染该页面。 以下 Thymeleaf 模板生成一个符合 /login 登录页面要求的 HTML 登录表单:spring-doc.cadn.net.cn

登录表单 - src/main/resources/templates/login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
	<head>
		<title>Please Log In</title>
	</head>
	<body>
		<h1>Please Log In</h1>
		<div th:if="${param.error}">
			Invalid username and password.</div>
		<div th:if="${param.logout}">
			You have been logged out.</div>
		<form th:action="@{/login}" method="post">
			<div>
			<input type="text" name="username" placeholder="Username"/>
			</div>
			<div>
			<input type="password" name="password" placeholder="Password"/>
			</div>
			<input type="submit" value="Log in" />
		</form>
	</body>
</html>

关于默认的 HTML 表单,有几点关键内容:spring-doc.cadn.net.cn

许多用户只需要自定义登录页面就足够了。 然而,如有需要,您可以通过额外的配置来自定义前面提到的所有内容。spring-doc.cadn.net.cn

如果你使用 Spring MVC,你需要一个控制器,将 GET /login 映射到我们创建的登录模板。 以下示例展示了一个最简化的 LoginControllerspring-doc.cadn.net.cn

LoginController
@Controller
class LoginController {
	@GetMapping("/login")
	String login() {
		return "login";
	}
}
@Controller
class LoginController {
    @GetMapping("/login")
    fun login(): String {
        return "login"
    }
}