此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Security 6.4.5! |
Spring MVC 集成
Spring Security 提供了许多与 Spring MVC 的可选集成。 本节将更详细地介绍集成。
@EnableWebMvcSecurity
从 Spring Security 4.0 开始, |
要启用 Spring Security 与 Spring MVC 的集成,请添加@EnableWebSecurity
注释添加到您的配置中。
Spring Security 使用 Spring MVC 的 |
PathPatternRequestMatcher 路径
Spring Security 提供了与 Spring MVC 在 URL 上的匹配方式的深度集成PathPatternRequestMatcher
.
这有助于确保您的 Security 规则与用于处理请求的逻辑匹配。
PathPatternRequestMatcher
必须使用相同的PathPatternParser
作为 Spring MVC。
如果您未自定义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
实例,您将需要在同一环境中配置 Spring Security 和 Spring MVCApplicationContext
.
我们始终建议您通过在 |
现在 Spring MVC 已与 Spring Security 集成,您可以编写一些将使用PathPatternRequestMatcher
.
@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 开始,我们可以通过添加 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
需要是最终的,它不能延长。
在这种情况下,UserDetailsService
可能会返回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 的依赖,使用应用程序将创建 |
-
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
到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 与 Callable 的
更从技术上讲,Spring Security 与 |
没有与DeferredResult
由 Controller 返回。
这是因为DeferredResult
由用户处理,因此无法自动与它集成。
但是,您仍然可以使用并发支持来提供与 Spring Security 的透明集成。
Spring MVC 和 CSRF 集成
Spring Security 与 Spring MVC 集成以添加 CSRF 保护。
自动 Token 包含
Spring Security 会自动将 CSRF 令牌包含在使用 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
添加到任何外部域。
在同一应用程序上下文中配置 Spring MVC 和 Spring Security
如果您使用的是 Boot,则默认情况下 Spring MVC 和 Spring Security 位于同一应用程序上下文中。
否则,对于 Java Config,包括两者@EnableWebMvc
和@EnableWebSecurity
将在同一上下文中构造 Spring Security 和 Spring MVC 组件。
Of,如果您正在使用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
in 放置在ApplicationContext
的DispatcherServlet
.