Spring MVC 集成

Spring Security 提供了多项与 Spring MVC 的可选集成。本节将详细介绍这些集成。

@EnableWebSecurity

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

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

PathPatternRequestMatcher

Spring Security 通过 PathPatternRequestMatcher 与 Spring MVC 如何匹配 URL 进行深度集成。这有助于确保您的安全规则与处理请求的逻辑相匹配。

PathPatternRequestMatcher 必须使用与 Spring MVC 相同的 PathPatternParser。如果您没有自定义 PathPatternParser,则可以执行以下操作

  • Java

  • Kotlin

  • Xml

@Bean
PathPatternRequestMatcherBuilderFactoryBean usePathPattern() {
	return new PathPatternRequestMatcherBuilderFactoryBean();
}
@Bean
fun usePathPattern(): PathPatternRequestMatcherBuilderFactoryBean {
    return PathPatternRequestMatcherBuilderFactoryBean()
}
<b:bean class="org.springframework.security.config.web.PathPatternRequestMatcherBuilderFactoryBean"/>

然后 Spring Security 将为您找到合适的 Spring MVC 配置。

如果您正在自定义 Spring MVC 的 PathPatternParser 实例,则需要在同一个 ApplicationContext 中配置 Spring Security 和 Spring MVC

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

通过匹配 HttpServletRequest 来提供授权规则是好的,因为它在代码路径中发生得很早,有助于减少攻击面。方法安全性确保即使有人绕过了 Web 授权规则,您的应用程序仍然是安全的。这被称为纵深防御

现在 Spring MVC 已与 Spring Security 集成,您已准备好编写一些将使用 PathPatternRequestMatcher授权规则

@AuthenticationPrincipal

Spring Security 提供了 AuthenticationPrincipalArgumentResolver,它可以自动解析 Spring MVC 参数的当前 Authentication.getPrincipal()。通过使用 @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 返回一个实现 UserDetails 和您自己的 CustomUser ObjectObject。可以使用以下代码访问当前已认证用户的 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 需要是 final,它就不能被扩展。在这种情况下,UserDetailsService 可能会返回一个实现 UserDetails 并提供一个名为 getCustomUser 的方法来访问 CustomUserObject

  • 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 表达式 来访问 CustomUser

  • 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 作为我们自己注解上的元注解来进一步消除对 Spring Security 的依赖。下一个示例演示了我们如何在名为 @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

我们将对 Spring Security 的依赖隔离到一个文件中。现在 @CurrentUser 已被指定,我们可以使用它来解析当前已认证用户的 CustomUser

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

一旦它是一个元注解,参数化也对您可用。

例如,考虑当您将 JWT 作为您的主体并且您想说明要检索哪个声明时。作为元注解,您可以这样做

  • Java

  • Kotlin

@Target({ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@AuthenticationPrincipal(expression = "claims['sub']")
public @interface CurrentUser {}
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.TYPE)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@AuthenticationPrincipal(expression = "claims['sub']")
annotation class CurrentUser

这已经相当强大了。但是,它也仅限于检索 sub 声明。

为了使其更灵活,首先发布 AnnotationTemplateExpressionDefaults bean,如下所示

  • Java

  • Kotlin

  • Xml

@Bean
public AnnotationTemplateExpressionDefaults templateDefaults() {
	return new AnnotationTemplateExpressionDeafults();
}
@Bean
fun templateDefaults(): AnnotationTemplateExpressionDefaults {
	return AnnotationTemplateExpressionDeafults()
}
<b:bean name="annotationExpressionTemplateDefaults" class="org.springframework.security.core.annotation.AnnotationTemplateExpressionDefaults"/>

然后您可以为 @CurrentUser 提供一个参数,如下所示

  • Java

  • Kotlin

@Target({ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@AuthenticationPrincipal(expression = "claims['{claim}']")
public @interface CurrentUser {
	String claim() default 'sub';
}
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.TYPE)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@AuthenticationPrincipal(expression = "claims['{claim}']")
annotation class CurrentUser(val claim: String = "sub")

这将允许您在您的应用程序集中以以下方式获得更大的灵活性

  • Java

  • Kotlin

@RequestMapping("/messages/inbox")
public ModelAndView findMessagesForUser(@CurrentUser("user_id") String userId) {

	// .. find messages for this user and return them ...
}
@RequestMapping("/messages/inbox")
open fun findMessagesForUser(@CurrentUser("user_id") userId: String?): ModelAndView {

    // .. find messages for this user and return them ...
}

Spring MVC 异步集成

Spring Web MVC 3.2+ 对异步请求处理有很好的支持。无需额外配置,Spring Security 会自动将 SecurityContext 设置到调用控制器返回的 CallableThread 中。例如,以下方法的 Callable 会自动在创建 Callable 时可用的 SecurityContext 中被调用

  • 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 与 Callable 关联

更确切地说,Spring Security 与 WebAsyncManager 集成。用于处理 CallableSecurityContext 是在调用 startCallableProcessing 时存在于 SecurityContextHolder 中的 SecurityContext

对于控制器返回的 DeferredResult 没有自动集成。这是因为 DeferredResult 由用户处理,因此无法自动集成。但是,您仍然可以使用并发支持来提供与 Spring Security 的透明集成。

Spring MVC 和 CSRF 集成

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

自动令牌包含

Spring Security 会自动在使用 Spring MVC 表单标签 的表单中包含 CSRF 令牌。考虑以下 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,它可以自动解析 Spring MVC 参数的当前 CsrfToken。通过使用@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 暴露给任何外部域。

在同一个 Application Context 中配置 Spring MVC 和 Spring Security

如果您使用 Boot,Spring MVC 和 Spring Security 默认在同一个应用程序上下文中。

否则,对于 Java Config,同时包含 @EnableWebMvc@EnableWebSecurity 将在同一个上下文中构建 Spring Security 和 Spring MVC 组件。

或者,如果您使用 ServletListener,您可以这样做

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

最后,对于 web.xml 文件,您按如下方式配置 DispatcherServlet

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

© . This site is unofficial and not affiliated with VMware.