授权 ServerHttpRequest

Spring Security 提供了对传入的 HTTP 请求进行授权的支持。 默认情况下,Spring Security 的授权会要求所有请求都经过身份验证。 显式的配置如下所示:spring-doc.cadn.net.cn

所有请求都需要经过身份验证的用户
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http
        .authorizeExchange((authorize) -> authorize
            .anyExchange().authenticated()
        )
        .httpBasic(withDefaults())
        .formLogin(withDefaults());
    return http.build();
}
@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
    return http {
        authorizeExchange {
            authorize(anyExchange, authenticated)
        }
        formLogin { }
        httpBasic { }
    }
}

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

多个授权请求规则
import static org.springframework.security.authorization.AuthorityReactiveAuthorizationManager.hasRole;
// ...
@Bean
SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) {
	http
		// ...
		.authorizeExchange((authorize) -> authorize                          (1)
			.pathMatchers("/resources/**", "/signup", "/about").permitAll()  (2)
			.pathMatchers("/admin/**").hasRole("ADMIN")                      (3)
			.pathMatchers("/db/**").access((authentication, context) ->      (4)
				hasRole("ADMIN").check(authentication, context)
					.filter(decision -> !decision.isGranted())
					.switchIfEmpty(hasRole("DBA").check(authentication, context))
			)
			.anyExchange().denyAll()                                         (5)
		);
	return http.build();
}
@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
    return http {
        authorizeExchange {                                                           (1)
            authorize(pathMatchers("/resources/**", "/signup", "/about"), permitAll)  (2)
            authorize("/admin/**", hasRole("ADMIN"))                                  (3)
            authorize("/db/**", { authentication, context ->                          (4)
                hasRole("ADMIN").check(authentication, context)
                    .filter({ decision -> !decision.isGranted() })
                    .switchIfEmpty(hasRole("DBA").check(authentication, context))
            })
            authorize(anyExchange, denyAll)                                           (5)
        }
        // ...
    }
}
1 指定了多条授权规则。 每条规则将按照其声明的顺序进行评估。
2 我们指定了多个URL模式,任何用户都可以访问。 具体来说,任何用户的请求如果URL以"/resources/"开头、等于"/signup"或等于"/about",都可以访问。
3 任何以 "/admin/" 开头的 URL 将仅限于具有 " ROLE_ADMIN" 权限的用户。 请注意,由于我们调用了 hasRole 方法,因此不需要指定 "ROLE_" 前缀。
4 任何以"/db/"开头的URL要求用户具有"ROLE_ADMIN"和"ROLE_DBA"角色。 这展示了提供自定义ReactiveAuthorizationManager的灵活性,允许我们实现任意授权逻辑。 为了简化示例,该样本使用了lambda表达式,并委托给现有的AuthorityReactiveAuthorizationManager.hasRole实现。 然而,在实际情况下,应用程序很可能会在一个适当的类中实现逻辑,该类实现了ReactiveAuthorizationManager接口。
5 任何尚未被匹配的 URL 都将被拒绝访问。 如果你不希望意外地忘记更新你的授权规则,这是一个很好的策略。