ошибка по запросу при использовании пружинной защиты - PullRequest
0 голосов
/ 13 марта 2020

Я программирую angular приложение Springboot. До использования Spring Security все работало нормально; когда я отображал домашнюю страницу, был сделан запрос на получение списка ProduitImmobilier

  loadData() {
    console.log('LOADDATA is called');
    Object.keys(this.search).forEach(key => key = null);
    this.search.page = 1;
    this.search.pageSize = 5;
    this.requestService.getListProduitImmobilierDTO(this.search).subscribe(
      articles => {this.annonces = articles;
                   this.collectionSize = articles[0].collectionSize; },
      (err: HttpErrorResponse) => {
        console.log('before display error');
        console.log(err);
        console.log('after display error');
      }
    );
  }

, а вот requestService

  getListProduitImmobilierDTO(search: Search): Observable<ProduitImmobilierDTO[]> {
    const headers: HttpHeaders = new HttpHeaders({ 'Content-Type': 'application/json' });
    headers.append('Access-Control-Allow-Origin: *', 'utf-8');
    const options = { headers };
    // tslint:disable-next-line: max-line-length
    return this.http.post<Search>('/api/produitimmobilier/all', JSON.stringify(search), options).pipe(map((search1: Search) => search1.result as ProduitImmobilierDTO[]));
  }

Но когда я добавил средство Spring Security, запрос отправил ошибку назад, вот фрагмент конфигурации

@Override
protected void configure(HttpSecurity http) throws Exception {
    http         
    .headers()
     .frameOptions().sameOrigin()
     .and()
       .authorizeRequests()
        .antMatchers("/**/*.scss", "/**/*.js","/**/*.html").permitAll()
           .antMatchers("/").permitAll()
           .antMatchers("/admin/**").hasRole("ADMIN")
           .anyRequest().authenticated()
           .and()
       .formLogin()
           .loginPage("/api/user/login?login=1")
           .defaultSuccessUrl("/")
           .failureUrl("/")
           .permitAll()
           .and()
       .logout()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        .logoutSuccessUrl("/")
        .deleteCookies("my-remember-me-cookie")
           .permitAll()
           .and()
        .rememberMe()
         //.key("my-secure-key")
         .rememberMeCookieName("my-remember-me-cookie")
         .tokenRepository(persistentTokenRepository())
         .tokenValiditySeconds(24 * 60 * 60)
         .and()
       .exceptionHandling()
       .and()
       .csrf().disable();
}

Предыдущий запрос, о котором я говорил, затем отправил обратно код ошибки 302

HEADER
URL de la requête : http://localhost:4200/api/produitimmobilier/all
Méthode de la requête : POST
Adresse distante : 127.0.0.1:4200
Code d’état :302
Version : HTTP/1.1

RESPONSE
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

Когда я отображаю ошибку от angular с помощью этого фрагмента кода

      (err: HttpErrorResponse) => {
        console.log('before display error');
        console.log(err);
        console.log('after display error');
      }

я получаю следующий вывод

error: SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
......
message: "Http failure during parsing for http://localhost:8080/api/user/login?login=1"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/api/user/login?login=1"

Прежде всего, я не понимаю, почему и как Spring Security перенаправляет запрос на loginForm url

Как глобально исправить ошибку?

Я должен добавить, что используется прокси на angular стороне приложения proxy.config. js

{
  "/api/*": {

    "target":  {
       "host": "localhost",
       "protocol": "http:",
       "port": 8080
     },
    "secure": false,
     "changeOrigin": true,
     "logLevel": "info"
  }
}

и я добавляю corMappings на задней стороне

/**
 * CORS configuration
 */
@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedOrigins(
                    "http://localhost:4200"
            )
            .allowedMethods(
                    "GET",
                    "PUT",
                    "POST",
                    "DELETE",
                    "PATCH",
                    "OPTIONS"
            );
}

1 Ответ

0 голосов
/ 14 марта 2020

Я нашел, как исправить неправильное поведение. Достаточно было добавить строку

.antMatchers("/**/*").permitAll()

в

@Override
protected void configure(HttpSecurity http) throws Exception {
    http         
    .headers()
     .frameOptions().sameOrigin()
     .and()
       .authorizeRequests()
        .antMatchers("/**/*.scss", "/**/*.js","/**/*.html").permitAll()
           .antMatchers("/**/*").permitAll()
           .antMatchers("/admin/**").hasRole("ADMIN")
           .anyRequest().authenticated()
           .and()
       .formLogin()
           .loginPage("/api/user/login")
           .defaultSuccessUrl("/")
           .failureUrl("/")
           .permitAll()
           .and()
       .logout()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...