Java:无法使用Angular 5将POST请求发送到后端

时间:2019-01-09 11:33:06

标签: java angular spring-boot

请帮助我。 我认为问题出在Spring Security。 我有一个基于Spring Boot的后端,前端是基于Angular 5。 当我尝试向后端发送发帖请求时,我遇到了这个问题:

从原点“ http://localhost:8080/administrateurs”到“ http://localhost:4200”处对XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:预检请求不允许重定向

RestController:

package smart.syndic.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import smart.syndic.dao.AdministrateursRepository;
import smart.syndic.entities.Administrateurs;

@RestController
@CrossOrigin("*")
public class AdministrateursRestController 
{
    @Autowired
    private AdministrateursRepository repository;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;



    @RequestMapping(value="/administrateurs", method=RequestMethod.POST)
    public Administrateurs postOne(@RequestBody Administrateurs s)
    {
        String password = s.getPassword();
        String encryptedPassword = bCryptPasswordEncoder
            .encode(password);
        s.setPassword(encryptedPassword);
        return repository.save(s);
    }



 }

Spring Security的SecurityConfig类:

package smart.syndic.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication
.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web
.builders.HttpSecurity;
import org.springframework.security.config.annotation.web
.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.
configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{   

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws 
    Exception 
    {   
        auth.inMemoryAuthentication()
        .withUser("admin").password("1234")
        .roles("ADMIN");
}

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder()
{
    return new BCryptPasswordEncoder();
}


@Override
protected void configure(HttpSecurity http) throws Exception 
{
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/login/**").permitAll();
    http.formLogin().loginPage("/login")
    .and().exceptionHandling().accessDeniedPage("/forbidden");
    http.authorizeRequests().anyRequest().authenticated();

    //When i remove this code it's works 
    }
}

Angular服务:

import {Injectable} from "@angular/core";
import {HttpClient, HttpHeaders, HttpParams, HttpRequest} from 
"@angular/common/http";

@Injectable()
 export class LoginService
{
  host:any = "http://localhost:8080/";

 constructor(private http:HttpClient)
{

}

 ajouterAdministrateurs(model:any)
{
    return this.http.post(this.host + "administrateurs", model);
}

谢谢。

2 个答案:

答案 0 :(得分:0)

希望这会有所帮助。

 public ajouterAdministrateurs(model: any) {
  const headers = new HttpHeaders({
   "Content-Type": "application/json",
   Authorization: "Basic " + btoa("username:password") //add your username and password of spring security
  });
  return this.http.post(this.host, model, {
   headers
  });
 }

答案 1 :(得分:0)

在您的SecurityConfig类中添加以下bean:

  @Bean
  public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(ImmutableList.of("*"));
    configuration.setAllowedMethods(ImmutableList.of("HEAD",
            "GET", "POST", "PUT", "DELETE", "PATCH","OPTIONS"));
    // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
    configuration.setAllowCredentials(true);
    // setAllowedHeaders is important! Without it, OPTIONS preflight request
    // will fail with 403 Invalid CORS request
    configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

您将需要这些导入:

import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;