Spring MVC Integration

Spring Security 提供了与 Spring MVC 的一些可选集成。本部分将详细介绍集成内容。

Spring Security provides a number of optional integrations with Spring MVC. This section covers the integration in further detail.

@EnableWebMvcSecurity

从 Spring Security 4.0 起,@EnableWebMvcSecurity 已弃用。替换项 @EnableWebSecurity 基于类路径增加了 Spring MVC 特性。

As of Spring Security 4.0, @EnableWebMvcSecurity is deprecated. The replacement is @EnableWebSecurity, which adds the Spring MVC features, based upon the classpath.

要启用 Spring Security 与 Spring MVC 的集成,请将 @EnableWebSecurity 注解添加到您的配置中。

To enable Spring Security integration with Spring MVC, add the @EnableWebSecurity annotation to your configuration.

Spring Security 使用 Spring MVC 的 link:https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/web.html#mvc-config-customize[WebMvcConfigurer 来提供配置。这意味着,如果您使用更高级的选项,例如直接与 WebMvcConfigurationSupport 集成,则需要手动提供 Spring Security 配置。

Spring Security provides the configuration by using Spring MVC’s WebMvcConfigurer. This means that, if you use more advanced options, such as integrating with WebMvcConfigurationSupport directly, you need to manually provide the Spring Security configuration.

MvcRequestMatcher

Spring Security 提供了深入的集成,说明 Spring MVC 如何通过 MvcRequestMatcher 匹配 URL。这有助于确保您的安全性规则与用于处理请求的逻辑相匹配。

Spring Security provides deep integration with how Spring MVC matches on URLs with MvcRequestMatcher. This is helpful to ensure that your Security rules match the logic used to handle your requests.

要使用 MvcRequestMatcher,您必须将 Spring Security 配置放在与 DispatcherServlet 相同的 ApplicationContext 中。这是必需的,因为 Spring Security 的 MvcRequestMatcher 期望您的 Spring MVC 配置注册一个名称为 mvcHandlerMappingIntrospectorHandlerMappingIntrospector bean,该 bean 用于执行匹配。

To use MvcRequestMatcher, you must place the Spring Security Configuration in the same ApplicationContext as your DispatcherServlet. This is necessary because Spring Security’s MvcRequestMatcher expects a HandlerMappingIntrospector bean with the name of mvcHandlerMappingIntrospector to be registered by your Spring MVC configuration that is used to perform the matching.

对于 web.xml 文件,这意味着您应将配置放在 DispatcherServlet.xml 中:

For a web.xml file, this means that you should place your configuration in the 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 放置在 DispatcherServletApplicationContext 中。

The following WebSecurityConfiguration in placed in the ApplicationContext of the DispatcherServlet.

  • 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("/")
    }
}

我们始终建议您通过匹配 HttpServletRequest 和方法安全性来提供授权规则。

We always recommend that you provide authorization rules by matching on the HttpServletRequest and method security.

通过与 `HttpServletRequest`匹配来提供授权规则很好,因为它会在代码路径中很早执行,并有助于减少 attack surface。方法安全性可确保,如果有人绕过了 Web 授权规则,您的应用程序仍受到保护。这称为 Defense in Depth

Providing authorization rules by matching on HttpServletRequest is good, because it happens very early in the code path and helps reduce the attack surface. Method security ensures that, if someone has bypassed the web authorization rules, your application is still secured. This is known as Defense in Depth

考虑如下映射的控制器:

Consider a controller that is mapped as follows:

  • Java

  • Kotlin

@RequestMapping("/admin")
public String admin() {
	// ...
}
@RequestMapping("/admin")
fun admin(): String {
    // ...
}

要将对该控制器方法的访问限制为管理员用户,您可以通过匹配 HttpServletRequest 以下内容提供授权规则:

To restrict access to this controller method to admin users, you can provide authorization rules by matching on the HttpServletRequest with the following:

  • Java

  • Kotlin

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
	http
		.authorizeHttpRequests((authorize) -> authorize
			.requestMatchers("/admin").hasRole("ADMIN")
		);
	return http.build();
}
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
    http {
        authorizeHttpRequests {
            authorize("/admin", hasRole("ADMIN"))
        }
    }
    return http.build()
}

以下清单在 XML 中执行相同的操作:

The following listing does the same thing in XML:

<http>
	<intercept-url pattern="/admin" access="hasRole('ADMIN')"/>
</http>

对于任一配置,/admin URL 要求经过身份验证的用户是管理员用户。但是,根据我们的 Spring MVC 配置,/admin.html URL 也映射到我们的 admin() 方法。此外,根据我们的 Spring MVC 配置,/admin URL 也映射到我们的 admin() 方法。

With either configuration, the /admin URL requires the authenticated user to be an admin user. However, depending on our Spring MVC configuration, the /admin.html URL also maps to our admin() method. Additionally, depending on our Spring MVC configuration, the /admin URL also maps to our admin() method.

问题在于我们的安全性规则只保护 /admin。我们可以在 Spring MVC 的所有排列中添加额外的规则,但这将非常冗长和繁琐。

The problem is that our security rule protects only /admin. We could add additional rules for all the permutations of Spring MVC, but this would be quite verbose and tedious.

幸运的是,使用 requestMatchers DSL 方法时,如果 Spring Security 检测到类路径中包含 Spring MVC,它将自动创建一个 MvcRequestMatcher。因此,它将基于 Spring MVC URL 匹配保护 Spring MVC 匹配的相同 URL。

Fortunately, when using the requestMatchers DSL method, Spring Security automatically creates a MvcRequestMatcher if it detects that Spring MVC is available in the classpath. Therefore, it will protect the same URLs that Spring MVC will match on by using Spring MVC to match on the URL.

使用 Spring MVC 时一个常见的要求是指定 servlet 路径属性,为此,您可以使用 MvcRequestMatcher.Builder 创建多个共享相同 servlet 路径的 MvcRequestMatcher 实例:

One common requirement when using Spring MVC is to specify the servlet path property, for that you can use the MvcRequestMatcher.Builder to create multiple MvcRequestMatcher instances that share the same servlet path:

  • Java

  • Kotlin

@Bean
public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {
	MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector).servletPath("/path");
	http
		.authorizeHttpRequests((authorize) -> authorize
			.requestMatchers(mvcMatcherBuilder.pattern("/admin")).hasRole("ADMIN")
			.requestMatchers(mvcMatcherBuilder.pattern("/user")).hasRole("USER")
		);
	return http.build();
}
@Bean
open fun filterChain(http: HttpSecurity, introspector: HandlerMappingIntrospector): SecurityFilterChain {
    val mvcMatcherBuilder = MvcRequestMatcher.Builder(introspector)
    http {
        authorizeHttpRequests {
            authorize(mvcMatcherBuilder.pattern("/admin"), hasRole("ADMIN"))
            authorize(mvcMatcherBuilder.pattern("/user"), hasRole("USER"))
        }
    }
    return http.build()
}

以下 XML 效果相同:

The following XML has the same effect:

<http request-matcher="mvc">
	<intercept-url pattern="/admin" access="hasRole('ADMIN')"/>
</http>

@AuthenticationPrincipal

Spring Security 提供 AuthenticationPrincipalArgumentResolver,可以为 Spring MVC 参数自动解析当前 Authentication.getPrincipal()。使用 @EnableWebSecurity 后,Spring MVC 配置自动添加该内容。如果您使用基于 XML 的配置,则必须自己添加此内容:

Spring Security provides AuthenticationPrincipalArgumentResolver, which can automatically resolve the current Authentication.getPrincipal() for Spring MVC arguments. By using @EnableWebSecurity, you automatically have this added to your Spring MVC configuration. If you use XML-based configuration, you must add this yourself:

<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。

Once you have properly configured AuthenticationPrincipalArgumentResolver, you can entirely decouple from Spring Security in your Spring MVC layer.

考虑一种情况:自定义 UserDetailsService 返回一个实现了 UserDetails 和您自己的 CustomUser ObjectObject。可以使用以下代码访问当前经过身份验证的用户的 CustomUser

Consider a situation where a custom UserDetailsService returns an Object that implements UserDetails and your own CustomUser Object. The CustomUser of the currently authenticated user could be accessed by using the following code:

  • 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 开始,我们可以通过添加注解更直接地解析参数:

As of Spring Security 3.2, we can resolve the argument more directly by adding an annotation:

  • 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 必须是 final 的,则无法扩展它。在这种情况下,UserDetailsService 可能返回一个实现了 UserDetails 并提供名为 getCustomUser 的方法用于访问 CustomUserObject

Sometimes, you may need to transform the principal in some way. For example, if CustomUser needed to be final, it could not be extended. In this situation, the UserDetailsService might return an Object that implements UserDetails and provides a method named getCustomUser to access 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
}

我们可以通过使用一个以 Authentication.getPrincipal() 为根对象的 SpEL expression 来访问 CustomUser

We could then access the CustomUser by using a SpEL expression that uses Authentication.getPrincipal() as the root object:

  • 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 来管理我们的用户,并且如果我们想要修改和保存当前用户的属性,可以使用以下内容:

We can also refer to beans in our SpEL expressions. For example, we could use the following if we were using JPA to manage our users and if we wanted to modify and save a property on the current user:

  • 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 设置为元注解进一步消除对 Spring Security 的依赖。以下示例演示了如何在名为 @CurrentUser 的注解上执行此操作。

We can further remove our dependency on Spring Security by making @AuthenticationPrincipal a meta-annotation on our own annotation. The next example demonstrates how we could do so on an annotation named @CurrentUser.

要消除对 Spring Security 的依赖,创建 @CurrentUser 的是消费应用程序。此步骤不是严格必需的,但有助于将您对 Spring Security 的依赖隔离到更中心的位置。

To remove the dependency on Spring Security, it is the consuming application that would create @CurrentUser. This step is not strictly required but assists in isolating your dependency to Spring Security to a more central location.

  • 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

我们已将对 Spring Security 的依赖隔离到了一个文件中。现在 @CurrentUser 已被指定,我们可使用它来发出信号以解析当前经过身份验证用户的 CustomUser

We have isolated our dependency on Spring Security to a single file. Now that @CurrentUser has been specified, we can use it to signal to resolve our CustomUser of the currently authenticated user:

  • 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 Async Integration

Spring Web MVC 3.2+ 对 Asynchronous Request Processing 有着出色的支持。Spring Security 自动将 SecurityContext 设置为 Thread,而 Thread 调用控制器返回的 Callable,而无需进行额外的配置。例如,以下方法会自动调用其 Callable,该 Callable 在创建 Callable 时可用:

Spring Web MVC 3.2+ has excellent support for Asynchronous Request Processing. With no additional configuration, Spring Security automatically sets up the SecurityContext to the Thread that invokes a Callable returned by your controllers. For example, the following method automatically has its Callable invoked with the SecurityContext that was available when the Callable was created:

  • 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"
    }
}
Associating SecurityContext to Callable’s

从技术角度讲,Spring Security 与 WebAsyncManager 集成。用于处理 CallableSecurityContext 是在调用 startCallableProcessing 时存在于 SecurityContextHolder 上的 SecurityContext

More technically speaking, Spring Security integrates with WebAsyncManager. The SecurityContext that is used to process the Callable is the SecurityContext that exists on the SecurityContextHolder when startCallableProcessing is invoked.

没有自动集成控制器返回的 DeferredResult。这是因为 `DeferredResult`是由用户处理的,因此无法与之自动集成。但是,您仍然可以使用 Concurrency Support提供与 Spring Security 的透明集成。

There is no automatic integration with a DeferredResult that is returned by controllers. This is because DeferredResult is processed by the users and, thus, there is no way of automatically integrating with it. However, you can still use Concurrency Support to provide transparent integration with Spring Security.

Spring MVC and CSRF Integration

Spring Security 集成 Spring MVC 以添加 CSRF 保护。

Spring Security integrates with Spring MVC to add CSRF protection.

Automatic Token Inclusion

Spring Security 自动 include the CSRF Token在使用 Spring MVC form tag的窗体中。考虑以下 JSP:

Spring Security automatically include the CSRF Token within forms that use the Spring MVC form tag. Consider the following 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:

The preceding example output HTMLs that is similar to the following:

<!-- ... -->

<form action="/context/logout" method="post">
<input type="submit" value="Log out"/>
<input type="hidden" name="_csrf" value="f81d4fae-7dec-11d0-a765-00a0c91e6bf6"/>
</form>

<!-- ... -->

Resolving the CsrfToken

Spring Security 提供 CsrfTokenArgumentResolver,它可以自动解析 Spring MVC 参数的当前 CsrfToken。通过使用 @EnableWebSecurity,您自动将其添加到 Spring MVC 配置中。如果您使用基于 XML 的配置,则必须自己添加此内容。

Spring Security provides CsrfTokenArgumentResolver, which can automatically resolve the current CsrfToken for Spring MVC arguments. By using @EnableWebSecurity, you automatically have this added to your Spring MVC configuration. If you use XML-based configuration, you must add this yourself.

正确配置 CsrfTokenArgumentResolver 后,您可以将 CsrfToken 暴露给基于静态 HTML 的应用程序:

Once CsrfTokenArgumentResolver is properly configured, you can expose the CsrfToken to your static HTML based application:

  • 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 非常重要。这意味着,如果您使用 Cross Origin Sharing (CORS),则应避免向任何外部域公开 CsrfToken

It is important to keep the CsrfToken a secret from other domains. This means that, if you use Cross Origin Sharing (CORS), you should NOT expose the CsrfToken to any external domains.