Spring Security OAuth2:多个ResourceServerConfiguration无法正常工作

时间:2017-12-19 20:36:39

标签: spring-boot spring-security spring-cloud spring-security-oauth2 spring-cloud-netflix

Spring boot版本:1.5.8.RELEASE Spring云版:Edgware.RELEASE(使用zuul)

尝试配置多个资源,并且在github中跟随this example无法使其正常工作。

我的代码是:

class ResourceServerConfigurationFactory
{
    static ResourceServerConfiguration criarResourceServerConfiguration(String resourceId, int order,
            HttpSecurityConfigurer configurer)
    {
        ResourceServerConfiguration resource = new ResourceServerConfiguration()
        {
            // Switch off the Spring Boot @Autowired configurers
            public void setConfigurers(List<ResourceServerConfigurer> configurers)
            {
                super.setConfigurers(configurers);
            }
        };

        resource.setConfigurers(Arrays.<ResourceServerConfigurer>asList(new ResourceServerConfigurerAdapter()
        {
            @Override
            public void configure(ResourceServerSecurityConfigurer resources) throws Exception
            {
                resources.resourceId(resourceId);
            }

            @Override
            public void configure(HttpSecurity http) throws Exception
            {
                configurer.configure(http);
            }
        }));

        resource.setOrder(order);

        return resource;
    }
}

interface HttpSecurityConfigurer
{
    public void configure(HttpSecurity http) throws Exception;
}

我的配置:

@Configuration
public class OAuthResourceConfiguration
{
    @Bean
    protected ResourceServerConfiguration usuarioResources()
    {
        return ResourceServerConfigurationFactory.criarResourceServerConfiguration("usuario", -10,
                http -> http.antMatcher("/user").authorizeRequests().anyRequest().permitAll());
    }

    @Bean
    protected ResourceServerConfiguration funcaoResources()
    {
        return ResourceServerConfigurationFactory.criarResourceServerConfiguration("funcao", -20,
                http -> http.antMatcher("/ws").authorizeRequests().anyRequest().permitAll());
    }   
}

最后,Spring启动应用程序:

@SpringBootApplication
@EnableResourceServer
@EnableZuulProxy
public class ApiGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }
}

事实:

  • Spring实例化两个ResourceServerConfiguration bean;
  • 只有具有更高阶的bean工作(/用户端点没问题,/ ws端点不断询问身份验证)
  • 在spring日志中,我可以看到只使用/ user ant matcher。 / ws完全被忽略了。

怎么了?

1 个答案:

答案 0 :(得分:0)

问题与我创建的Factory类有关。

lambda +匿名类的组合造成了一些问题(我无法理解)搞砸了。

在@Configuration类中将两个Configurers声明为Bean都解决了问题。