I want to implement a authentication system with Spring Boot and Spring Security. I did some googling, watched some YouTube videos and implemented the functionality. The Signup route that I have written in a Controller, works just fine. I have not written any implementation for login route because Spring Security takes care of login functionality itself. Now the issue is, when I add Global CORS configuration like this
@Configuration
@EnableWebSecurity
public class AppConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").allowedOrigins("http://localhost:3000").allowedMethods("*");
}
}
the CORS configuration works fine for the signup route that I have written but not for login route which Spring security provides me. ( My signup route is "/api/signup" and login route is "/api/login". I have changed login route from "/login" to "/api/login" using customAuthenticationFilter.setFilterProcessesUrl("/api/login"); where customAuthenticationFilter is a auth filter. ). Please can anyone help regarding this. I am trying to access the Spring Boot backend using React frontend. On hitting "/api/signup" there is no error whatsoever but on hitting "/api/login" it shows
Access to XMLHttpRequest at 'http://localhost:8080/api/login' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource..
Following is Security config
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsService userDetailsService;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
public SecurityConfig(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
this.userDetailsService = userDetailsService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(
bCryptPasswordEncoder
);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter(authenticationManager());
customAuthenticationFilter.setFilterProcessesUrl("/api/login");
http.csrf().disable();
http.sessionManagement().sessionCreationPolicy(STATELESS);
http.authorizeRequests().antMatchers("/api/login", "/api/refreshtoken", "/api/signup").permitAll();
http.authorizeRequests().antMatchers(GET, "/api/userprofile").hasAuthority("USER");
http.authorizeRequests().anyRequest().authenticated();
http.addFilter(customAuthenticationFilter);
http.addFilterBefore(new CustomAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Bean
@Override
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
}```