对于最新的稳定版本,请使用 Spring Security 6.5.3spring-doc.cadn.net.cn

表单登录

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

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

登录URL身份验证入口点
图 1.重定向到登录页面

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

1号首先,用户向资源 (/private)未授权。spring-doc.cadn.net.cn

2号Spring Security 的FilterSecurityInterceptor表示通过抛出AccessDeniedException.spring-doc.cadn.net.cn

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

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

5号应用程序中的某些内容必须呈现登录页面spring-doc.cadn.net.cn

提交用户名和密码后,UsernamePasswordAuthenticationFilter验证用户名和密码。 这UsernamePasswordAuthenticationFilterextends AbstractAuthenticationProcessingFilter,因此下图应该看起来非常相似:spring-doc.cadn.net.cn

用户名密码身份验证过滤器
图 2.验证用户名和密码

该图建立在我们的SecurityFilterChain图。spring-doc.cadn.net.cn

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

2号接下来,UsernamePasswordAuthenticationToken被传递到AuthenticationManager要验证的实例。 什么的细节AuthenticationManager看起来取决于用户信息的存储方式。spring-doc.cadn.net.cn

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

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

  2. RememberMeServices.loginFail被调用。 如果记住我没有配置,这是一个无作。 请参阅RememberMeServicesJavadoc 中的接口。spring-doc.cadn.net.cn

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

4号如果身份验证成功,则成功spring-doc.cadn.net.cn

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

  2. 身份验证是在 SecurityContextHolder 上设置的。 请参阅SecurityContextPersistenceFilter类。spring-doc.cadn.net.cn

  3. RememberMeServices.loginSuccess被调用。 如果记住我没有配置,这是一个无作。 请参阅RememberMeServicesJavadoc 中的接口。spring-doc.cadn.net.cn

  4. ApplicationEventPublisher发布一个InteractiveAuthenticationSuccessEvent.spring-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.: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到我们创建的登录模板。 以下示例显示了最小的LoginController:spring-doc.cadn.net.cn

登录控制器
@Controller
class LoginController {
	@GetMapping("/login")
	String login() {
		return "login";
	}
}
@Controller
class LoginController {
    @GetMapping("/login")
    fun login(): String {
        return "login"
    }
}