Spring Boot OAuth2Client - обработка входа в Facebook

Добрый день,

У меня есть приложение весенней загрузки, которое работает по адресу: 8080. Основная его функция - обработать GET-запрос "login / facebook" и сделать там правильный вход. Это хорошо работает, когда запрос отправляется с того же домена (например, с http://localhost:8080/help страница справки).

Это реализовано таким образом:

@Configuration
@EnableOAuth2Client
public class SclLoginSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private OAuth2ClientContext oauth2ClientContext;

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

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
    }

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

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

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

    private Filter ssoFilter(ClientResources client, String path) {
        OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(path);
        OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
        filter.setRestTemplate(template);
        filter.setTokenServices(new UserInfoTokenServices(
                client.getResource().getUserInfoUri(), client.getClient().getClientId()));
        return filter;
    }

    class ClientResources {
        @NestedConfigurationProperty
        private AuthorizationCodeResourceDetails client = new AuthorizationCodeResourceDetails();

        @NestedConfigurationProperty
        private ResourceServerProperties resource = new ResourceServerProperties();

        public AuthorizationCodeResourceDetails getClient() {
            return client;
        }

        public ResourceServerProperties getResource() {
            return resource;
        }
    }
}

Фильтр Cors существует и реализован таким образом:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

Свойства приложения, связанные с Facebook:

facebook.client.client-id=...
facebook.client.client-secret=...
facebook.client.access-token-uri=https://graph.facebook.com/oauth/access_token
facebook.client.user-authorization-uri=https://www.facebook.com/dialog/oauth
facebook.client.token-name=oauth_token
facebook.client.authentication-scheme=query
facebook.client.client-authentication-scheme=form
facebook.resource.user-info-uri=https://graph.facebook.com/me

С другой стороны - я занимаюсь разработкой презентационного уровня (реакция + осевое приложение), который размещен по адресу: 8000, где я собирался вызвать GET на " http://localhost:8080/login/facebook " и перенаправить на страница входа в Facebook, но этого никогда не было. Вместо этого я получаю в браузере:

XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?client_id=...&redirect_uri=http://localhost:8080/login/facebook&response_type=code&state=335Pc0. Redirect from 'https://www.facebook.com/dialog/oauth?client_id=...&redirect_uri=http://localhost:8080/login/facebook&response_type=code&state=335Pc0' to 'https://www.facebook.com/login.php?skip_api_login=1&api_key=..._&display=page&locale=en_US&logger_id=13caa792-a9a9-4187-bdb3-732702703d31' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

В то же время, журналы со стороны пружины загрузки:

[nio-8080-exec-4] o.s.s.web.DefaultRedirectStrategy        : Redirecting to 'https://www.facebook.com/dialog/oauth?client_id=...&redirect_uri=http://localhost:8080/login/facebook&response_type=code&state=335Pc0'

Может кто-нибудь посоветовать, как включить этот вариант использования?

Очень ценю внимание и ответ,

Виталий

1 ответ

Решение

Решение было сложным: 1. сделать 8080 в качестве сервера авторизации (Server). 2. приложение host 8000 внутри весенней загрузки mvc (клиент), включите аутентификацию на сервере

Решение, очень похожее на описанное здесь: как защитить сервис Spring Boot RESTful с OAuth2 и входом в систему Social

Другие вопросы по тегам