对于最新的稳定版本,请使用 Spring Security 6.5.3! |
Spring MVC 集成
Spring Security 提供了许多与 Spring MVC 的可选集成。本节更详细地介绍了集成。
@EnableWebMvcSecurity
从 Spring Security 4.0 开始,@EnableWebMvcSecurity 已弃用。替换为@EnableWebSecurity 这将决定根据类路径添加 Spring MVC 功能。 |
要启用 Spring Security 与 Spring MVC 的集成,请将@EnableWebSecurity
注释添加到您的配置中。
Spring Security 使用 Spring MVC 的 WebMvcConfigurer 提供配置。这意味着,如果您使用更高级的选项,例如与WebMvcConfigurationSupport 直接,那么你需要手动提供 Spring Security 配置。 |
MvcRequest匹配器
Spring Security 提供了与 Spring MVC 在 URL 上匹配的方式的深度集成MvcRequestMatcher
. 这有助于确保安全规则与用于处理请求的逻辑匹配。
为了使用MvcRequestMatcher
您必须将 Spring Security 配置放在相同的ApplicationContext
作为您的DispatcherServlet
. 这是必要的,因为 Spring Security 的MvcRequestMatcher
期望HandlerMappingIntrospector
bean 的名称为mvcHandlerMappingIntrospector
由用于执行匹配的 Spring MVC 配置注册。
对于一个web.xml
这意味着您应该将配置放在DispatcherServlet.xml
.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- All Spring Configuration (both MVC and Security) are in /WEB-INF/spring/ -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/*.xml</param-value>
</context-param>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- Load from the ContextLoaderListener -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
下面WebSecurityConfiguration
放置在DispatcherServlet
sApplicationContext
.
-
Java
-
Kotlin
public class SecurityInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { RootConfiguration.class,
WebMvcConfiguration.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
class SecurityInitializer : AbstractAnnotationConfigDispatcherServletInitializer() {
override fun getRootConfigClasses(): Array<Class<*>>? {
return null
}
override fun getServletConfigClasses(): Array<Class<*>> {
return arrayOf(
RootConfiguration::class.java,
WebMvcConfiguration::class.java
)
}
override fun getServletMappings(): Array<String> {
return arrayOf("/")
}
}
始终建议通过匹配 |
考虑映射如下的控制器:
-
Java
-
Kotlin
@RequestMapping("/admin")
public String admin() {
@RequestMapping("/admin")
fun admin(): String {
如果我们想将对此控制器方法的访问权限限制为管理员用户,开发人员可以通过匹配HttpServletRequest
替换为以下内容:
-
Java
-
Kotlin
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.antMatchers("/admin").hasRole("ADMIN")
);
return http.build();
}
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeRequests {
authorize(AntPathRequestMatcher("/admin"), hasRole("ADMIN"))
}
}
return http.build()
}
或在 XML 中
<http>
<intercept-url pattern="/admin" access="hasRole('ADMIN')"/>
</http>
使用任一配置,URL/admin
将要求经过身份验证的用户是管理员用户。但是,根据我们的 Spring MVC 配置,URL/admin.html
也会映射到我们的admin()
方法。 此外,根据我们的 Spring MVC 配置,URL/admin/
也会映射到我们的admin()
方法。
问题是我们的安全规则只是保护/admin
. 我们可以为 Spring MVC 的所有排列添加额外的规则,但这将非常冗长和乏味。
相反,我们可以利用 Spring Security 的MvcRequestMatcher
. 以下配置将通过使用 Spring MVC 在 URL 上匹配来保护 Spring MVC 将匹配的相同 URL。
-
Java
-
Kotlin
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.mvcMatchers("/admin").hasRole("ADMIN")
);
// ...
}
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeRequests {
authorize("/admin", hasRole("ADMIN"))
}
}
// ...
}
或在 XML 中
<http request-matcher="mvc">
<intercept-url pattern="/admin" access="hasRole('ADMIN')"/>
</http>
@AuthenticationPrincipal
Spring Security 提供AuthenticationPrincipalArgumentResolver
可以自动解析当前Authentication.getPrincipal()
用于 Spring MVC 参数。
通过使用@EnableWebSecurity
您将自动将其添加到您的 Spring MVC 配置中。
如果您使用基于 XML 的配置,则必须自己添加。
例如:
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver" />
</mvc:argument-resolvers>
</mvc:annotation-driven>
一次AuthenticationPrincipalArgumentResolver
配置正确,则可以与 Spring MVC 层中的 Spring Security 完全解耦。
考虑这样一种情况:UserDetailsService
返回一个Object
实现UserDetails
和您自己的CustomUser
Object
.这CustomUser
可以使用以下代码访问当前经过身份验证的用户:
-
Java
-
Kotlin
@RequestMapping("/messages/inbox")
public ModelAndView findMessagesForUser() {
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
CustomUser custom = (CustomUser) authentication == null ? null : authentication.getPrincipal();
// .. find messages for this user and return them ...
}
@RequestMapping("/messages/inbox")
open fun findMessagesForUser(): ModelAndView {
val authentication: Authentication = SecurityContextHolder.getContext().authentication
val custom: CustomUser? = if (authentication as CustomUser == null) null else authentication.principal
// .. find messages for this user and return them ...
}
从 Spring Security 3.2 开始,我们可以通过添加注释来更直接地解决参数。例如:
-
Java
-
Kotlin
import org.springframework.security.core.annotation.AuthenticationPrincipal;
// ...
@RequestMapping("/messages/inbox")
public ModelAndView findMessagesForUser(@AuthenticationPrincipal CustomUser customUser) {
// .. find messages for this user and return them ...
}
@RequestMapping("/messages/inbox")
open fun findMessagesForUser(@AuthenticationPrincipal customUser: CustomUser?): ModelAndView {
// .. find messages for this user and return them ...
}
有时可能需要以某种方式改造本金。
例如,如果CustomUser
需要是最终的,它不能延长。
在这种情况下,UserDetailsService
might 返回一个Object
实现UserDetails
并提供了一个名为getCustomUser
访问CustomUser
.
例如,它可能如下所示:
-
Java
-
Kotlin
public class CustomUserUserDetails extends User {
// ...
public CustomUser getCustomUser() {
return customUser;
}
}
class CustomUserUserDetails(
username: String?,
password: String?,
authorities: MutableCollection<out GrantedAuthority>?
) : User(username, password, authorities) {
// ...
val customUser: CustomUser? = null
}
-
Java
-
Kotlin
import org.springframework.security.core.annotation.AuthenticationPrincipal;
// ...
@RequestMapping("/messages/inbox")
public ModelAndView findMessagesForUser(@AuthenticationPrincipal(expression = "customUser") CustomUser customUser) {
// .. find messages for this user and return them ...
}
import org.springframework.security.core.annotation.AuthenticationPrincipal
// ...
@RequestMapping("/messages/inbox")
open fun findMessagesForUser(@AuthenticationPrincipal(expression = "customUser") customUser: CustomUser?): ModelAndView {
// .. find messages for this user and return them ...
}
我们也可以在 SpEL 表达式中引用 Bean。 例如,如果我们使用 JPA 来管理我们的用户,并且我们想要修改和保存当前用户的属性,则可以使用以下内容。
-
Java
-
Kotlin
import org.springframework.security.core.annotation.AuthenticationPrincipal;
// ...
@PutMapping("/users/self")
public ModelAndView updateName(@AuthenticationPrincipal(expression = "@jpaEntityManager.merge(#this)") CustomUser attachedCustomUser,
@RequestParam String firstName) {
// change the firstName on an attached instance which will be persisted to the database
attachedCustomUser.setFirstName(firstName);
// ...
}
import org.springframework.security.core.annotation.AuthenticationPrincipal
// ...
@PutMapping("/users/self")
open fun updateName(
@AuthenticationPrincipal(expression = "@jpaEntityManager.merge(#this)") attachedCustomUser: CustomUser,
@RequestParam firstName: String?
): ModelAndView {
// change the firstName on an attached instance which will be persisted to the database
attachedCustomUser.setFirstName(firstName)
// ...
}
我们可以通过将@AuthenticationPrincipal
我们自己的注释的元注释。
下面我们演示如何在名为@CurrentUser
.
重要的是要认识到,为了消除对 Spring Security 的依赖,使用应用程序会创建@CurrentUser .
此步骤不是严格必需的,但有助于将您对 Spring Security 的依赖项隔离到更中心的位置。 |
-
Java
-
Kotlin
@Target({ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@AuthenticationPrincipal
public @interface CurrentUser {}
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.TYPE)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@AuthenticationPrincipal
annotation class CurrentUser
既然@CurrentUser
已指定,我们可以用它来发出信号来解析我们的CustomUser
当前已验证的用户。
我们还将对 Spring Security 的依赖隔离到一个文件。
-
Java
-
Kotlin
@RequestMapping("/messages/inbox")
public ModelAndView findMessagesForUser(@CurrentUser CustomUser customUser) {
// .. find messages for this user and return them ...
}
@RequestMapping("/messages/inbox")
open fun findMessagesForUser(@CurrentUser customUser: CustomUser?): ModelAndView {
// .. find messages for this user and return them ...
}
Spring MVC 异步集成
Spring Web MVC 3.2+ 对异步请求处理有出色的支持。
无需额外配置,Spring Security 将自动设置SecurityContext
到Thread
调用Callable
由您的控制器返回。
例如,以下方法将自动拥有其Callable
使用SecurityContext
当Callable
创建:
-
Java
-
Kotlin
@RequestMapping(method=RequestMethod.POST)
public Callable<String> processUpload(final MultipartFile file) {
return new Callable<String>() {
public Object call() throws Exception {
// ...
return "someView";
}
};
}
@RequestMapping(method = [RequestMethod.POST])
open fun processUpload(file: MultipartFile?): Callable<String> {
return Callable {
// ...
"someView"
}
}
将 SecurityContext 与可调用对象的
从技术上讲,Spring Security 与 |
没有与DeferredResult
由控制器返回。
这是因为DeferredResult
由用户处理,因此无法自动与其集成。
但是,您仍然可以使用并发支持来提供与 Spring Security 的透明集成。
Spring MVC 和 CSRF 集成
自动包含Tokens
Spring Security 将自动将 CSRF Tokens包含在使用 Spring MVC 表单标记的表单中。 例如,以下 JSP:
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:form="http://www.springframework.org/tags/form" version="2.0">
<jsp:directive.page language="java" contentType="text/html" />
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<!-- ... -->
<c:url var="logoutUrl" value="/logout"/>
<form:form action="${logoutUrl}"
method="post">
<input type="submit"
value="Log out" />
<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>
</form:form>
<!-- ... -->
</html>
</jsp:root>
将输出类似于以下内容的 HTML:
<!-- ... -->
<form action="/context/logout" method="post">
<input type="submit" value="Log out"/>
<input type="hidden" name="_csrf" value="f81d4fae-7dec-11d0-a765-00a0c91e6bf6"/>
</form>
<!-- ... -->
解析 CsrfToken
Spring Security 提供CsrfTokenArgumentResolver
可以自动解析当前CsrfToken
用于 Spring MVC 参数。
通过使用@EnableWebSecurity您将自动将其添加到您的 Spring MVC 配置中。
如果您使用基于 XML 的配置,则必须自己添加。
一次CsrfTokenArgumentResolver
配置正确,则可以公开CsrfToken
到基于静态 HTML 的应用程序。
-
Java
-
Kotlin
@RestController
public class CsrfController {
@RequestMapping("/csrf")
public CsrfToken csrf(CsrfToken token) {
return token;
}
}
@RestController
class CsrfController {
@RequestMapping("/csrf")
fun csrf(token: CsrfToken): CsrfToken {
return token
}
}
保持CsrfToken
来自其他域的秘密。
这意味着,如果您使用的是跨域共享 (CORS),则不应公开CsrfToken
到任何外部域。