0

I am having some issues with my angular + springboot website..

When i try to get from by backend, it works just fine.

BUT when i try to POST (add new user) to the backend, i get an error:

Access to XMLHttpRequest at 'http://localhost:8080/api/users/add' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

POST http://localhost:8080/api/users/add net::ERR_FAILED

My frontend service:

  addUser(user: User): void{
const HTTP_OPTIONS = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'Content-Type',
    'Access-Control-Allow-Methods': 'GET,POST, PUT, DELETE'
  })
};
const body = JSON.stringify(user);
console.log(body);

this.httpClient.post('http://localhost:8080/api/users/add', body, HTTP_OPTIONS).subscribe(
  (data: any) => {
    this.emitIntervenantsSubject(data);
    this.goToMainRoute();
  },
  (error) => {
    const message = 'server issue';
    this.emitErrorsSubject(message );
  }
);

}

backend:

UserController.java

  @RestController
  @RequestMapping("api/users")
  public class UserController {

  ....

  @CrossOrigin(origins = "http://localhost:8080")
  @PostMapping(path = "/add")
  public User addUser(@RequestBody User user){

  return userService.addUser(user);

  }

userService.java

public interface UserService {

Optional<User> getUser(Long id);
Optional <List<User>> getUsers(Long ... id);

User addUser(User user);
 }

UserServiceimpl.java:

@Service 
public class UserServiceimpl implements UserService {
private UserRepo userRepo;

..........


 @Override
 public User addUser(User user) {
return this.userRepo.save(user);
 }

SecurityConfigurer.java:

@Configuration
@EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {

  private PasswordEncoder passwordEncoder;

  private final SecretKey secretKey;
  private final JwtConfig jwtConfig;

  public SecurityConfigurer(SecretKey secretKey, JwtConfig jwtConfig) {
    this.secretKey = secretKey;
    this.jwtConfig = jwtConfig;
  }

  @Autowired
  public void ApplicationSecurityConfig(PasswordEncoder passwordEncoder){
   this.passwordEncoder = passwordEncoder;
  }

  protected void configure(HttpSecurity http) throws Exception{
     http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
    .addFilter(new JwtUsernameAndPasswordAuthenticationFilter(authenticationManager(), jwtConfig, 
      secretKey))
    .addFilterAfter(new JwtTokenVerifier(secretKey, jwtConfig), 
            JwtUsernameAndPasswordAuthenticationFilter.class)
    .authorizeRequests().antMatchers("/api/**").permitAll()
    .anyRequest()
    .authenticated();
  }
 }

Here is the request body:

{"id":2,"interfaceName":"User","fname":"test","lname":"test","email":"test@gmail.com","phone":"1112223333","address":"1 test","username":"test","password":"121212","role":"I","active":true}

Here is the users DB table:

users DB table

thank you !

lucca450
  • 19
  • 2
  • 1. Enable CORS with Spring Security. 2. Remove all the Access-Control headers on the client. These are server response headers. 3. FYI @CrossOrigin should include the origins you want to allow, not the API origin. Here's some more info about [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) – Paul Samsotha Apr 10 '21 at 04:55
  • Hi ! How would I enable CORS with Spring security? How can I add those headers to the server response? So my @CrossOrigin should I coude my local host 4200 and not the 8080? – lucca450 Apr 10 '21 at 05:01
  • https://www.baeldung.com/spring-security-cors-preflight – Paul Samsotha Apr 10 '21 at 05:22

0 Answers0