1

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

从源“ 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);
    }



 }

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 
    }
}

角服务:

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);
}

谢谢。

4

2 回答 2

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
  });
 }
于 2019-01-09T12:10:17.197 回答
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;
于 2019-01-09T13:47:39.633 回答