问题在于@EnableResourceServer 导入了ResourceServerConfiguration,其阶数为3,远远优于ManagementServerProperties.ACCESS_OVERRIDE_ORDER。
请参阅有关执行器安全性和排序配置类的 Spring Boot 文档:http://docs.spring.io/spring-boot/docs/1.4.3.RELEASE/reference/htmlsingle/#boot-features-security-actuator
默认执行器安全配置比仅允许访问 /health 端点并阻止其余部分要聪明得多,它实际上会根据 management.port 和 management.contextPath 而变化,而且很难找到正确的管理端点 URL,不会在您的安全性中留下巨大的漏洞或弄乱您自己的资源。
如果你想保持自动配置管理安全的好处,有两个选择:
编辑:a) 使用 BeanPostProcessor 降低 ResourceServerConfiguration 顺序
@dsyer 在 github 线程上提出了这项改进:
@Component
@Slf4j
public class ResourceServerConfigurationPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof ResourceServerConfiguration) {
LOGGER.debug("Lowering order of ResourceServerConfiguration bean : {}", beanName);
ResourceServerConfiguration config = (ResourceServerConfiguration) bean;
config.setOrder(SecurityProperties.ACCESS_OVERRIDE_ORDER);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
我刚刚用这个类替换了下面的代码,它运行良好。
编辑:b) 手动覆盖 ResourceServerConfiguration 顺序
如果你因为某种原因不喜欢后处理器,你可以用另一个配置类替换@EnableResourceServer,它的顺序将在默认管理安全之后:
/**
* Extend the default resource server config class, and downgrade its order
*/
public class ResourceServerLowPrecedenceConfiguration extends ResourceServerConfiguration {
/**
* This is enough to override Spring Boot's default resource security,
* but it does not takes over the management.
*/
@Override
public int getOrder() {
return SecurityProperties.ACCESS_OVERRIDE_ORDER;
}
}
还有你自己的配置类:
/** @EnableResourceServer is replaced by @Import using the low precedence config */
@Configuration
@Import(ResourceServerLowPrecedenceConfiguration.class)
public class YourOwnOAuth2Config extends ResourceServerConfigurerAdapter {
@Override
public void configure(final HttpSecurity http) throws Exception {
// Secure your resources using OAuth 2.0 here
}
}
编辑:您还可以重写自己的 @EnableResourceServer 注释以快捷方式 @Import :
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(ResourceServerLowPrecedenceConfiguration.class)
public @interface EnableResourceServer {
}
恕我直言,当 spring-security-oauth 在类路径上时,这应该是默认行为。
请参阅关于 GitHub 问题的讨论:
https://github.com/spring-projects/spring-boot/issues/5072