此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Security 6.4.3spring-doc.cadn.net.cn

Spring MVC 集成

Spring Security 提供了许多与 Spring MVC 的可选集成。 本节将更详细地介绍集成。spring-doc.cadn.net.cn

@EnableWebMvcSecurity

从 Spring Security 4.0 开始,@EnableWebMvcSecurity已弃用。 替代是@EnableWebSecurity这将决定根据 Classpath 添加 Spring MVC 功能。

要启用 Spring Security 与 Spring MVC 的集成,请添加@EnableWebSecurity注释添加到您的配置中。spring-doc.cadn.net.cn

Spring Security 使用 Spring MVC 的WebMvcConfigurer提供配置。 这意味着,如果您使用的是更高级的选项,例如与WebMvcConfigurationSupport直接提供,则需要手动提供 Spring Security 配置。

MvcRequestMatcher

Spring Security 提供了与 Spring MVC 在 URL 上的匹配方式的深度集成MvcRequestMatcher. 这有助于确保您的 Security 规则与用于处理请求的逻辑匹配。spring-doc.cadn.net.cn

为了使用MvcRequestMatcher您必须将 Spring Security Configuration 放在相同的ApplicationContext作为您的DispatcherServlet. 这是必要的,因为 Spring Security 的MvcRequestMatcher期望HandlerMappingIntrospectorbean 的名称为mvcHandlerMappingIntrospector由用于执行匹配的 Spring MVC 配置注册。spring-doc.cadn.net.cn

对于web.xml这意味着您应该将配置放在DispatcherServlet.xml.spring-doc.cadn.net.cn

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

下面WebSecurityConfigurationin 放置在DispatcherServletsApplicationContext.spring-doc.cadn.net.cn

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和方法安全性。spring-doc.cadn.net.cn

通过匹配HttpServletRequest很好,因为它发生在代码路径的早期,有助于减少攻击面。 方法安全性可确保在有人绕过 Web 授权规则的情况下,您的应用程序仍然受到保护。 这就是所谓的深度防御spring-doc.cadn.net.cn

考虑一个映射如下的控制器:spring-doc.cadn.net.cn

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

如果我们想将对此控制器方法的访问限制为管理员用户,开发人员可以通过匹配HttpServletRequest替换为以下内容:spring-doc.cadn.net.cn

@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 格式spring-doc.cadn.net.cn

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

无论使用哪种配置,URL/admin将要求经过身份验证的用户是管理员用户。 但是,根据我们的 Spring MVC 配置,URL/admin.html也会映射到我们的admin()方法。 此外,根据我们的 Spring MVC 配置,URL/admin/也会映射到我们的admin()方法。spring-doc.cadn.net.cn

问题在于,我们的安全规则只是保护/admin. 我们可以为 Spring MVC 的所有排列添加额外的规则,但这将非常冗长和乏味。spring-doc.cadn.net.cn

幸运的是,在使用requestMatchersDSL 方法,Spring Security 会自动创建一个MvcRequestMatcher如果它检测到 Spring MVC 在 Classpath 中可用。 因此,它将通过使用 Spring MVC 匹配 URL 来保护 Spring MVC 将匹配的相同 URL。spring-doc.cadn.net.cn

使用 Spring MVC 时的一个常见要求是指定 servlet path 属性,为此你可以使用MvcRequestMatcher.Builder创建多个MvcRequestMatcher共享同一 servlet 路径的实例:spring-doc.cadn.net.cn

@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()
}

@AuthenticationPrincipal

Spring Security 提供AuthenticationPrincipalArgumentResolver可以自动解析当前的Authentication.getPrincipal()对于 Spring MVC 参数。 通过使用@EnableWebSecurity你会自动将其添加到你的 Spring MVC 配置中。 如果使用基于 XML 的配置,则必须自行添加此配置。 例如:spring-doc.cadn.net.cn

<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 完全解耦。spring-doc.cadn.net.cn

考虑自定义UserDetailsService返回一个Object实现UserDetails和你自己的CustomUser Object.这CustomUser可以使用以下代码访问当前经过身份验证的用户:spring-doc.cadn.net.cn

@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 开始,我们可以通过添加 Comments 来更直接地解决参数。例如:spring-doc.cadn.net.cn

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 ...
}

Sometimes it may be necessary 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 returns an Object that implements UserDetails and provides a method named getCustomUser to access CustomUser. For example, it might look like:spring-doc.cadn.net.cn

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
}

We could then access the CustomUser using a SpEL expression that uses Authentication.getPrincipal() as the root object:spring-doc.cadn.net.cn

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 ...
}

We can also refer to Beans in our SpEL expressions. For example, the following could be used if we were using JPA to manage our Users and we wanted to modify and save a property on the current user.spring-doc.cadn.net.cn

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)

    // ...
}

We can further remove our dependency on Spring Security by making @AuthenticationPrincipal a meta annotation on our own annotation. Below we demonstrate how we could do this on an annotation named @CurrentUser.spring-doc.cadn.net.cn

It is important to realize that in order 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.
@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

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

@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+ has excellent support for Asynchronous Request Processing. With no additional configuration, Spring Security will automatically setup the SecurityContext to the Thread that invokes a Callable returned by your controllers. For example, the following method will automatically have its Callable invoked with the SecurityContext that was available when the Callable was created:spring-doc.cadn.net.cn

@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

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 at the time startCallableProcessing is invoked.spring-doc.cadn.net.cn

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-doc.cadn.net.cn

Spring MVC and CSRF Integration

Automatic Token Inclusion

Spring Security will automatically include the CSRF Token within forms that use the Spring MVC form tag. For example, the following JSP:spring-doc.cadn.net.cn

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

Will output HTML that is similar to the following:spring-doc.cadn.net.cn

<!-- ... -->

<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 provides CsrfTokenArgumentResolver which can automatically resolve the current CsrfToken for Spring MVC arguments. By using @EnableWebSecurity you will automatically have this added to your Spring MVC configuration. If you use XML based configuration, you must add this yourself.spring-doc.cadn.net.cn

Once CsrfTokenArgumentResolver is properly configured, you can expose the CsrfToken to your static HTML based application.spring-doc.cadn.net.cn

@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
    }
}

It is important to keep the CsrfToken a secret from other domains. This means if you are using Cross Origin Sharing (CORS), you should NOT expose the CsrfToken to any external domains.spring-doc.cadn.net.cn