Spring REST аутентификация - Chrome игнорирует куки - PullRequest
0 голосов
/ 12 января 2019

У меня есть внешний интерфейс в React и внутренний в Spring Boot, и я пытаюсь получить REST-аутентификацию. Проблема в том, что я получаю заголовок Set-Cookie: JSESSIONID=221DC95570C24409E1F21B1ED954BDA9; Path=/; HttpOnly, но на самом деле chrome никогда не устанавливает cookie, поэтому после входа в систему, когда я пытаюсь вызвать конечную точку с помощью axios и withCredentials: true, я получаю 401, как будто я пытаюсь без аутентификации достичь своего конечная точка бэкэнда. Я где-то читал, что cookie-файлы никогда не устанавливаются, потому что интерфейс - localhost:3000. Есть ли способ обойти это? Или лучший способ настроить REST-аутентификацию через Spring? Без полной аутентификации вручную.

SecurityConfig

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

  @Autowired
  private RESTAuthenticationEntryPoint authenticationEntryPoint;
  @Autowired
  private RESTAuthenticationFailureHandler authenticationFailureHandler;
  @Autowired
  private RESTAuthenticationSuccessHandler authenticationSuccessHandler;
  @Autowired
  private CustomAuthenticationProvider customAuthProvider;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.addFilterBefore(new CorsFilter(), SessionManagementFilter.class);
    http.cors();
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/api/*/public/**", "/api/security/**", "/api/auth/**").permitAll().anyRequest().authenticated();
    http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).accessDeniedHandler(new CustomAccessDeniedHandler());
    http.formLogin().loginProcessingUrl("/api/auth/login").successHandler(authenticationSuccessHandler);
    http.formLogin().failureHandler(authenticationFailureHandler);
    http.logout().logoutUrl("/api/auth/logout").invalidateHttpSession(true).logoutSuccessHandler((new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK)));
  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(customAuthProvider);
  }

  @Bean
  public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(ImmutableList.of("http://localhost:3000"));
    configuration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type", "x-csrf-token", "Access-Control-Allow-Credentials"));
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
  }

}

WebConfig

@Configuration
public class WebConfig implements WebMvcConfigurer {

  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry
        .addMapping("/**").allowedOrigins("http://localhost:3000").allowedMethods("GET", "POST", "OPTIONS", "PUT", "OPTIONS").allowedHeaders("Content-Type",
            "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", "x-csrf-token")
        .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials").allowCredentials(true).maxAge(3600);
  }

}

Еще один вопрос, есть идеи, почему CORS везде установлен на localhost, но аутентифицированные конечные точки возвращают подстановочный знак? Это может быть потому, что он выбрасывает в настоящее время 401 для них?

EDIT:

Запрос на вход enter image description here

Аутентифицированная конечная точка пользователя enter image description here

Весенний журнал говорит, что не аутентифицирован (понятно)

2019-01-12 21:04:09.281 DEBUG 13320 --- [nio-8091-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@64212f9d: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
...