对于最新的稳定版本,请使用 Spring Security 6.4.1spring-doc.cadn.net.cn

使用 AuthorizationFilter 授权 HttpServletRequests

本节以 Servlet 体系结构和实现为基础,深入探讨了授权在基于 Servlet 的应用程序中的工作原理。spring-doc.cadn.net.cn

AuthorizationFilter取代FilterSecurityInterceptor. 为了保持向后兼容,FilterSecurityInterceptor仍然是默认值。 本节讨论如何AuthorizationFilter有效以及如何覆盖默认配置。

AuthorizationFilter提供HttpServletRequests. 它作为 Security Filters 之一插入到 FilterChainProxy 中。spring-doc.cadn.net.cn

您可以在声明SecurityFilterChain. 而不是使用authorizeRequestsauthorizeHttpRequests这样:spring-doc.cadn.net.cn

使用 authorizeHttpRequests
@Bean
SecurityFilterChain web(HttpSecurity http) throws AuthenticationException {
    http
        .authorizeHttpRequests((authorize) -> authorize
            .anyRequest().authenticated();
        )
        // ...

    return http.build();
}

这改进了authorizeRequests以多种方式:spring-doc.cadn.net.cn

  1. 使用简化的AuthorizationManagerAPI 而不是元数据源、配置属性、决策管理器和投票者。 这简化了重用和定制。spring-doc.cadn.net.cn

  2. 延误Authentication查找。 它不需要为每个请求查找身份验证,而只会在授权决策需要身份验证的请求中查找身份验证。spring-doc.cadn.net.cn

  3. 基于 Bean 的配置支持。spring-doc.cadn.net.cn

什么时候authorizeHttpRequests替换为authorizeRequests然后AuthorizationFilter替换为FilterSecurityInterceptor.spring-doc.cadn.net.cn

authorization过滤器
图 1.授权 HttpServletRequest

我们可以通过按优先顺序添加更多规则来将 Spring Security 配置为具有不同的规则。spring-doc.cadn.net.cn

授权请求
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
	http
		// ...
		.authorizeHttpRequests(authorize -> authorize                                  (1)
			.requestMatchers("/resources/**", "/signup", "/about").permitAll()         (2)
			.requestMatchers("/admin/**").hasRole("ADMIN")                             (3)
			.requestMatchers("/db/**").access(new WebExpressionAuthorizationManager("hasRole('ADMIN') and hasRole('DBA')"))   (4)
			// .requestMatchers("/db/**").access(AuthorizationManagers.allOf(AuthorityAuthorizationManager.hasRole("ADMIN"), AuthorityAuthorizationManager.hasRole("DBA")))   (5)
			.anyRequest().denyAll()                                                (6)
		);

	return http.build();
}
1 指定了多个授权规则。 每个规则都按照其声明的顺序进行考虑。
2 我们指定了任何用户都可以访问的多个 URL 模式。 具体而言,如果 URL 以“/resources/”开头、等于“/signup”或等于“/about”,则任何用户都可以访问请求。
3 任何以 “/admin/” 开头的 URL 都将被限制为具有 “ROLE_ADMIN” 角色的用户。 您会注意到,由于我们正在调用hasRole方法,则不需要指定 “ROLE_” 前缀。
4 任何以 “/db/” 开头的 URL 都要求用户同时具有 “ROLE_ADMIN” 和 “ROLE_DBA”。 您会注意到,由于我们使用的是hasRole表达式,则不需要指定 “ROLE_” 前缀。
5 4 中的相同规则,可以通过组合多个来编写AuthorizationManager.
6 任何尚未匹配的 URL 都将被拒绝访问。 如果您不想意外忘记更新授权规则,这是一个很好的策略。

您可以通过构建自己的方法来采用基于 bean 的方法RequestMatcherDelegatingAuthorizationManager这样:spring-doc.cadn.net.cn

配置 RequestMatcherDelegatingAuthorizationManager
@Bean
SecurityFilterChain web(HttpSecurity http, AuthorizationManager<RequestAuthorizationContext> access)
        throws AuthenticationException {
    http
        .authorizeHttpRequests((authorize) -> authorize
            .anyRequest().access(access)
        )
        // ...

    return http.build();
}

@Bean
AuthorizationManager<RequestAuthorizationContext> requestMatcherAuthorizationManager(HandlerMappingIntrospector introspector) {
    MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector);
    RequestMatcher permitAll =
            new AndRequestMatcher(
                    mvcMatcherBuilder.pattern("/resources/**"),
                    mvcMatcherBuilder.pattern("/signup"),
                    mvcMatcherBuilder.pattern("/about"));
    RequestMatcher admin = mvcMatcherBuilder.pattern("/admin/**");
    RequestMatcher db = mvcMatcherBuilder.pattern("/db/**");
    RequestMatcher any = AnyRequestMatcher.INSTANCE;
    AuthorizationManager<HttpServletRequest> manager = RequestMatcherDelegatingAuthorizationManager.builder()
            .add(permitAll, (context) -> new AuthorizationDecision(true))
            .add(admin, AuthorityAuthorizationManager.hasRole("ADMIN"))
            .add(db, AuthorityAuthorizationManager.hasRole("DBA"))
            .add(any, new AuthenticatedAuthorizationManager())
            .build();
    return (context) -> manager.check(context.getRequest());
}

您还可以为任何请求匹配器连接自己的自定义授权管理器spring-doc.cadn.net.cn

以下是将自定义授权管理器映射到my/authorized/endpoint:spring-doc.cadn.net.cn

自定义授权管理器
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests((authorize) -> authorize
            .requestMatchers("/my/authorized/endpoint").access(new CustomAuthorizationManager());
        )
        // ...

    return http.build();
}

或者你可以为所有请求提供它,如下所示:spring-doc.cadn.net.cn

所有请求的自定义授权管理器
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests((authorize) -> authorize
            .anyRequest().access(new CustomAuthorizationManager());
        )
        // ...

    return http.build();
}

默认情况下,AuthorizationFilter适用于所有 Dispatcher 类型。 我们可以将 Spring Security 配置为不将授权规则应用于所有调度程序类型,方法是使用shouldFilterAllDispatcherTypes方法:spring-doc.cadn.net.cn

将 shouldFilterAllDispatcherTypes 设置为 false
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests((authorize) -> authorize
            .shouldFilterAllDispatcherTypes(false)
            .anyRequest().authenticated()
        )
        // ...

    return http.build();
}

而不是设置shouldFilterAllDispatcherTypesfalse,建议的方法是自定义 Dispatcher 类型的授权。 例如,您可能希望授予对 dispatcher 类型为ASYNCFORWARD.spring-doc.cadn.net.cn

允许 ASYNC 和 FORWARD 调度程序类型
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests((authorize) -> authorize
            .dispatcherTypeMatchers(DispatcherType.ASYNC, DispatcherType.FORWARD).permitAll()
            .anyRequest().authenticated()
        )
        // ...

    return http.build();
}

您还可以对其进行自定义,以要求调度程序类型的特定角色:spring-doc.cadn.net.cn

需要 ADMIN 的 Dispatcher 类型 ERROR
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests((authorize) -> authorize
            .dispatcherTypeMatchers(DispatcherType.ERROR).hasRole("ADMIN")
            .anyRequest().authenticated()
        )
        // ...

    return http.build();
}

请求匹配器

RequestMatcherinterface 用于确定请求是否与给定规则匹配。 我们使用securityMatchers来确定给定的HttpSecurity应应用于给定请求。 同样,我们可以使用requestMatchers来确定我们应该应用于给定请求的授权规则。 请看下面的例子:spring-doc.cadn.net.cn

@Configuration
@EnableWebSecurity
public class SecurityConfig {

	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		http
			.securityMatcher("/api/**")                            (1)
			.authorizeHttpRequests(authorize -> authorize
				.requestMatchers("/user/**").hasRole("USER")       (2)
				.requestMatchers("/admin/**").hasRole("ADMIN")     (3)
				.anyRequest().authenticated()                      (4)
			)
			.formLogin(withDefaults());
		return http.build();
	}
}
1 配置HttpSecurity仅应用于以/api/
2 允许访问以/user/对于具有USER角色
3 允许访问以/admin/对于具有ADMIN角色
4 与上述规则不匹配的任何其他请求都需要身份验证

securityMatcher(s)requestMatcher(s)方法将决定哪些RequestMatcherimplementation 最适合您的应用程序:如果 Spring MVC 在 Classpath 中,则MvcRequestMatcher,否则,AntPathRequestMatcher将被使用。 您可以在此处阅读有关 Spring MVC 集成的更多信息。spring-doc.cadn.net.cn

如果您想使用特定的RequestMatcher,只需将实现传递给securityMatcher和/或requestMatcher方法:spring-doc.cadn.net.cn

import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher; (1)
import static org.springframework.security.web.util.matcher.RegexRequestMatcher.regexMatcher;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		http
			.securityMatcher(antMatcher("/api/**"))                              (2)
			.authorizeHttpRequests(authorize -> authorize
				.requestMatchers(antMatcher("/user/**")).hasRole("USER")         (3)
				.requestMatchers(regexMatcher("/admin/.*")).hasRole("ADMIN")     (4)
				.requestMatchers(new MyCustomRequestMatcher()).hasRole("SUPERVISOR")     (5)
				.anyRequest().authenticated()
			)
			.formLogin(withDefaults());
		return http.build();
	}
}

public class MyCustomRequestMatcher implements RequestMatcher {

    @Override
    public boolean matches(HttpServletRequest request) {
        // ...
    }
}
1 导入静态工厂方法AntPathRequestMatcherRegexRequestMatcher创建RequestMatcher实例。
2 配置HttpSecurity仅应用于以/api/AntPathRequestMatcher
3 允许访问以/user/对于具有USER角色, 使用AntPathRequestMatcher
4 允许访问以/admin/对于具有ADMIN角色, 使用RegexRequestMatcher
5 允许访问与MyCustomRequestMatcher对于具有SUPERVISOR角色, 使用自定义RequestMatcher

表达 式

建议您使用类型安全的授权管理器而不是 SPEL。 然而WebExpressionAuthorizationManager可用于帮助迁移旧版 SPEL。spring-doc.cadn.net.cn

要使用WebExpressionAuthorizationManager,您可以使用尝试迁移的表达式构造一个 Importing,如下所示:spring-doc.cadn.net.cn

.requestMatchers("/test/**").access(new WebExpressionAuthorizationManager("hasRole('ADMIN') && hasRole('USER')"))

如果你在表达式中引用一个 bean,如下所示:@webSecurity.check(authentication, request),建议您改为直接调用 Bean,它看起来类似于以下内容:spring-doc.cadn.net.cn

.requestMatchers("/test/**").access((authentication, context) ->
    new AuthorizationDecision(webSecurity.check(authentication.get(), context.getRequest())))

对于包含 Bean 引用以及其他表达式的复杂指令,建议您更改这些指令以实现AuthorizationManager并通过调用.access(AuthorizationManager).spring-doc.cadn.net.cn

如果您无法执行此作,则可以配置DefaultHttpSecurityExpressionHandler替换为 bean 解析器,并将其提供给WebExpressionAuthorizationManager#setExpressionhandler.spring-doc.cadn.net.cn


APP信息