![](/img/trans.png)
[英]Cannot send a POST request that contain an object (foreign key) with Angular 5 to Rest Backend based on Spring Boot
[英]Java : Cannot send POST request to backend with Angular 5
请我帮忙。 我认为问题出在Spring Security。 我有一个基于Spring Boot的后端,该前端基于Angular5。当我尝试向后端发送发布请求时,我遇到了以下问题:
从源' http:// localhost:4200 '在' http:// localhost:8080 / administrateurs '处对XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:不允许重定向起飞前的要求。
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);
}
}
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
}
}
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);
}
谢谢。
希望这可以帮助。
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
});
}
在您的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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.