无法从主应用程序类外部获取application.yml属性

时间:2017-07-16 20:15:14

标签: java spring-boot

我是Spring Boot的新手,也是Java的新手。我正在使用Github OAuth2 sample application from Spring's documentation。开箱即用,一切都按预期工作,但是,当我尝试将 facebook() github()方法移动到新类时,他们无法获取信息来自src / main / resources / application.yml文件。我尝试使用与主Application类相同的包中的类,并尝试将该类放在另一个包中。

src / main / resources / application.yml(所有客户信息均直接来自文档)

security:
  oauth2:
    client:
      client-id: acme
      client-secret: acmesecret
      scope: read,write
      auto-approve-scopes: '.*'

facebook:
  client:
    clientId: 233668646673605
    clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
    accessTokenUri: https://graph.facebook.com/oauth/access_token
    userAuthorizationUri: https://www.facebook.com/dialog/oauth
    tokenName: oauth_token
    authenticationScheme: query
    clientAuthenticationScheme: form
  resource:
    userInfoUri: https://graph.facebook.com/me
github:
  client:
    clientId: bd1c0a783ccdd1c9b9e4
    clientSecret: 1a9030fbca47a5b2c28e92f19050bb77824b5ad1
    accessTokenUri: https://github.com/login/oauth/access_token
    userAuthorizationUri: https://github.com/login/oauth/authorize
    clientAuthenticationScheme: form
  resource:
    userInfoUri: https://api.github.com/user

logging:
  level:
    org.springframework.security: DEBUG

工作申请

具有单个包的目录结构,该包包含主Application类中的所有内容,但类 ClientResources.java

除外

Application.java

package com.github.example;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter;
import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.filter.CompositeFilter;

@SpringBootApplication
@RestController
@EnableOAuth2Client
@EnableAuthorizationServer
@Order(6)
public class Application extends WebSecurityConfigurerAdapter implements Serializable {

    private static final long serialVersionUID = 7526472295622776147L;

    @Autowired
    OAuth2ClientContext oauth2ClientContext;

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

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {
            System.out.println("Ready to Authenticate!");
        };
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http.antMatcher("/**")
                .authorizeRequests()
                .antMatchers("/", "/login**", "/webjars/**")
                .permitAll()
                .anyRequest()
                .authenticated().and().exceptionHandling()
                .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/"))
                .and().logout().logoutSuccessUrl("/").permitAll().and().csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .and().addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
        // @formatter:on
    }

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            // @formatter:off
            http.antMatcher("/me")
                .authorizeRequests()
                .anyRequest()
                .authenticated();
            // @formatter:on
        }
    }

    @Bean
    public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(filter);
        registration.setOrder(-100);
        return registration;
    }

    @Bean
    @ConfigurationProperties("facebook")
    public ClientResources facebook() {
        return new ClientResources();
    }

    @Bean
    @ConfigurationProperties("github")
    public ClientResources github() {
        return new ClientResources();
    }

    private Filter ssoFilter() {
        CompositeFilter filter = new CompositeFilter();
        List<Filter> filters = new ArrayList<>();
        filters.add(ssoFilter(facebook(), "/login/facebook"));
        filters.add(ssoFilter(github(), "/login/github"));
        filter.setFilters(filters);
        return filter;
    }

    private Filter ssoFilter(ClientResources client, String path) {
        OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationFilter
            = new OAuth2ClientAuthenticationProcessingFilter(path);
        OAuth2RestTemplate oAuth2RestTemplate
            = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);

        oAuth2ClientAuthenticationFilter.setRestTemplate(oAuth2RestTemplate);
        UserInfoTokenServices tokenServices = new UserInfoTokenServices(
                client.getResource().getUserInfoUri(),
                client.getClient().getClientId()
        );

        tokenServices.setRestTemplate(oAuth2RestTemplate);
        oAuth2ClientAuthenticationFilter.setTokenServices(tokenServices);

        return oAuth2ClientAuthenticationFilter;
    }

}

ClientResources.java     package com.github.example;

import java.io.Serializable;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;

public class ClientResources implements Serializable {

    private static final long serialVersionUID = 7526472295622776147L;

    @NestedConfigurationProperty
    private AuthorizationCodeResourceDetails client = new AuthorizationCodeResourceDetails();

    @NestedConfigurationProperty
    private ResourceServerProperties resource = new ResourceServerProperties();

    public AuthorizationCodeResourceDetails getClient() {
        return client;
    }

    public ResourceServerProperties getResource() {
        return resource;
    }
}

在从src / main / resources / application.yml中检索信息时,将应用程序分解为多个类中断

我这里有两个包:

  1. com.github.example
  2. com.github.example.providers
  3. com.github.example.Application.java

    package com.github.example;
    
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.List;
    import javax.servlet.Filter;
    
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ApplicationContext;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.annotation.Order;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.oauth2.client.OAuth2ClientContext;
    import org.springframework.security.oauth2.client.OAuth2RestTemplate;
    import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter;
    import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter;
    import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
    import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
    import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
    import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
    import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
    import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
    import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.filter.CompositeFilter;
    
    import com.github.example.providers.*;
    
    @SpringBootApplication
    @RestController
    @EnableOAuth2Client
    @EnableAuthorizationServer
    @Order(6)
    public class Application extends WebSecurityConfigurerAdapter implements Serializable {
    
        private static final long serialVersionUID = 7526472295622776147L;
    
        @Autowired
        OAuth2ClientContext oauth2ClientContext;
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
        @Bean
        public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
            return args -> {
                System.out.println("Ready to Authenticate!");
            };
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // @formatter:off
            http.antMatcher("/**")
                    .authorizeRequests()
                    .antMatchers("/", "/login**", "/webjars/**")
                    .permitAll()
                    .anyRequest()
                    .authenticated().and().exceptionHandling()
                    .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/"))
                    .and().logout().logoutSuccessUrl("/").permitAll().and().csrf()
                    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                    .and().addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
            // @formatter:on
        }
    
        @Configuration
        @EnableResourceServer
        protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
            @Override
            public void configure(HttpSecurity http) throws Exception {
                // @formatter:off
                http.antMatcher("/me")
                    .authorizeRequests()
                    .anyRequest()
                    .authenticated();
                // @formatter:on
            }
        }
    
        @Bean
        public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
            FilterRegistrationBean registration = new FilterRegistrationBean();
            registration.setFilter(filter);
            registration.setOrder(-100);
            return registration;
        }
    
        @Bean
        @ConfigurationProperties("github")
        public ProviderResources github() {
            return new ProviderResources();
        }
    
        private Filter ssoFilter() {
            Facebook fb = new Facebook();
            CompositeFilter filter = new CompositeFilter();
            List<Filter> filters = new ArrayList<>();
            filters.add(ssoFilter(fb.getConfig(), "/login/facebook"));
            filters.add(ssoFilter(github(), "/login/github"));
            filter.setFilters(filters);
            return filter;
        }
    
        private Filter ssoFilter(ProviderResources client, String path) {
            OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationFilter
                = new OAuth2ClientAuthenticationProcessingFilter(path);
            OAuth2RestTemplate oAuth2RestTemplate
                = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
    
            oAuth2ClientAuthenticationFilter.setRestTemplate(oAuth2RestTemplate);
            UserInfoTokenServices tokenServices = new UserInfoTokenServices(
                    client.getResource().getUserInfoUri(),
                    client.getClient().getClientId()
            );
    
            tokenServices.setRestTemplate(oAuth2RestTemplate);
            oAuth2ClientAuthenticationFilter.setTokenServices(tokenServices);
    
            return oAuth2ClientAuthenticationFilter;
        }
    
    }
    

    com.github.example.providers.ProviderResources.java

    package com.github.example.providers;
    
    import java.io.Serializable;
    import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
    import org.springframework.boot.context.properties.NestedConfigurationProperty;
    import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
    
    public class ProviderResources implements Serializable {
    
        private static final long serialVersionUID = 7526472295622776147L;
    
        @NestedConfigurationProperty
        private AuthorizationCodeResourceDetails client = new AuthorizationCodeResourceDetails();
    
        @NestedConfigurationProperty
        private ResourceServerProperties resource = new ResourceServerProperties();
    
        public AuthorizationCodeResourceDetails getClient() {
            return client;
        }
    
        public ResourceServerProperties getResource() {
            return resource;
        }
    }
    

    com.github.example.providers.Facebook.java

    package com.github.example.providers;
    
    import java.io.Serializable;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.stereotype.Component;
    
    @Component
    @ConfigurationProperties("facebook")
    public class Facebook  implements Serializable {
        private static final long serialVersionUID = 7526472295622776147L;
    
        @Bean
        @ConfigurationProperties("facebook")
        public ProviderResources getConfig() {
            return new ProviderResources();
        }
    }
    

    结果 在破碎的源代码中,github登录仍然有效,但是,当尝试使用Facebook登录时,我收到以下500错误:

    Whitelabel Error Page
    
    This application has no explicit mapping for /error, so you are seeing this as a fallback.
    
    Sun Jul 16 16:10:19 EDT 2017
    There was an unexpected error (type=Internal Server Error, status=500).
    HTTP URL must not be null
    

    调试结果 在调试时,我注意到ProviderResources()中的变量为null。使用 @Value 注释设置属性值时,我注意到相同的结果。带有 @Value 注释的属性值在主Application类中正确设置,但在任何其他类中都设置为null。

    同样,我是Spring boot / java的新手,我可能正在做一些新手。感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

在不起作用的代码中,您正在创建一个新的Facebook bean,它不是Spring Application Context中的Facebook bean。

由于您需要绑定到Facebook Spring bean对象的属性,因此您需要注入Facebook Spring bean,并创建一个Spring Application Context不知道的新对象。

从ssoFilter()方法中删除Facebook fb = new Facebook();并注入Facebook对象。

一种选择是注入Facebook Spring bean对象:

@Autowired
private Facebook fb;

private Filter ssoFilter() {        
    CompositeFilter filter = new CompositeFilter();
    List<Filter> filters = new ArrayList<>();
    filters.add(ssoFilter(fb.getConfig(), "/login/facebook"));
    filters.add(ssoFilter(github(), "/login/github"));
    filter.setFilters(filters);
    return filter;
}