trouble connecting Angular 10 with Spring security to use custom login page

352 views Asked by At

I have been working on a web application using Spring boot and spring security with frontend controlled by angular 10. I have implemented backend for security and created a login page also. But, on running on local host it is throwing an error

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.

I have been banging my head all day long to resolve this error but could not find the solution. I have attached my code below for reference

Controller

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public boolean login(@RequestBody loginDetails data) {
        try {
            String username = data.getUsername();
            System.out.println("Checking...");
            System.out.println(data.getUsername());
            System.out.println(data.getPassword());
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, data.getPassword()));
            // String token = jwtTokenProvider.createToken(username,
            // this.users.findByEmail(username).getRoles());
            System.out.println("abcdefg");
            Map<Object, Object> model = new HashMap<>();
            model.put("username", username);
            // model.put("token", token);
            /* return true; */
        } catch (AuthenticationException e) {
            /*
             * throw new BadCredentialsException("Invalid email/password supplied");
             */
            return false;
        }
        return true;
    }

WebSecurityConfiguration

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Qualifier("userDetailsService")
    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {

        return new BCryptPasswordEncoder();
    }

    
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/user/save","/user/login",    
                "/admin/**").permitAll().anyRequest().authenticated().and().csrf()
                .disable().formLogin().permitAll().and().logout().permitAll();
        http.cors();
    }
     
    @Bean
    public AuthenticationManager customAuthenticationManager() throws Exception {
        return authenticationManager();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

}

AngularRequestcode

public doLogin(){

      this.userLogin.username=this.loginForm.get("username").value;
      this.userLogin.password=this.loginForm.get("password").value;
      console.log(this.userLogin);
    return this.http.post<any>("http://localhost:8080/user/login",this.userLogin).subscribe((response) => {
    
              if (response.status === 200) {
                  
                console.log('login successfully');
    
              } else {
    
                console.log('galat');
    
              }
  
            }
        );
  }
1

There are 1 answers

0
mzhehalo On BEST ANSWER

First of all, try change to:

@Override
protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().cors().and()
        .authorizeRequests().antMatchers("/user/save", "/user/login",
                "/admin/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll()
                .and().logout().permitAll();
    }

CORS it's browser check if you have response with: Access-Control-Allow-Origin: http://localhost:4200 or no: No 'Access-Control-Allow-Origin' header is present on the requested resource.; Change http://localhost:4200 to your front-end url; And add to your WebSecurityConfig:

@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:4200")
                .allowedMethods("*");
    }
and: implements WebMvcConfigurer

Response without error: Response without error:

Response with error. No Access-Control-Allow-Origin: Response with error. No Access-Control-Allow-Origin: