title: Angular2 with Spring Boot and Spring Security
body: <p>First of all, I already check the question at <a href="https://stackoverflow.com/questions/40106799/angular2-spring-boot-security">this page</a> and I try his solution but at the end, I still have the same issue. </p>
  
  <blockquote>
    <p>XMLHttpRequest cannot load <a href="http://localhost:8080/login" rel="nofollow noreferrer">http://localhost:8080/login</a>. 
        Response to preflight request doesn't pass access control check: 
        No 'Access-Control-Allow-Origin' header is present on the requested resource. 
        Origin '<a href="http://localhost:3000" rel="nofollow noreferrer">http://localhost:3000</a>' is therefore not allowed access. 
        The response had HTTP status code 403.</p>
  </blockquote>
  
  <p>However, I put an <code>access-control</code> everywhere so I don't understand why it's like this.</p>
  
  <p>My code looks like this (I hope I will put enough for you):</p>
  
  <p>In Angular, my <code>login.service.ts</code>: </p>
  
  <pre><code>check(name: string, password: string): boolean {
       let headers = new Headers();
      headers.append('Content-Type', 'application/x-www-form-urlencoded');
      headers.append('Access-Control-Allow-Origin','*');
      let options = new RequestOptions({headers:headers,withCredentials:true});
  
      if(this.http.post(this.baseUrl, 
          `username=${name}&amp;password=${password}`,
          {headers:headers})
          .toPromise().then(response=&gt; {
            return {}
          }))
          return true;    
  
          return false;
    }
  </code></pre>
  
  <p>I also want to return a boolean if the authentication succeed but I don't really know how to know if it works, so I do it like that for now (and it's always true).</p>
  
  <p>Then, in Java, I have this code:</p>
  
  <pre class="lang-java prettyprint-override"><code>@Configuration
  @EnableWebMvc
  class WebConfig extends WebMvcConfigurerAdapter {
  }
  </code></pre>
  
  <p>then for the security, I got this :</p>
  
  <pre class="lang-java prettyprint-override"><code>@Configuration
  @EnableWebSecurity
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
  
      @Autowired
      private RESTLoginSuccessHandler loginSuccessHandler;
  
      @Autowired
      private RestLogoutSuccessHandler logoutSuccessHandler;
  
      @Override
      protected void configure(HttpSecurity httpSecurity) throws Exception {
          //deactivate CSRF and use custom impl for CORS
          httpSecurity
                  .cors.and()
                  .csrf().disable()
                  .addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class);
          //authorize, authenticate rest
          httpSecurity
                  .authorizeRequests()
                      .anyRequest().hasRole("USER")
                      .and()
                  .sessionManagement()
                      .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                      .and()
                  .formLogin()
                      .usernameParameter("username")
                      .passwordParameter("password")
                      .loginPage("/login")
                      .successHandler(loginSuccessHandler)
                      .permitAll()
                      .and()
                  .logout()
                      .logoutSuccessHandler(this.logoutSuccessHandler)
                      .permitAll();
      }
  
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
          auth.inMemoryAuthentication().withUser("rano").password("1234").roles("USER");
          auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER", "ADMIN");
      }
  }
  
  @Bean
  CorsConfigurationSource corsConfigurationSource() {
      CorsConfiguration configuration = new CorsConfiguration();
  
      configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080","http://localhost:3000"));
  
      configuration.setAllowedMethods(Arrays.asList("PUT","DELETE","POST"));
      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      source.registerCorsConfiguration("/**", configuration);
      return source;
  }
  </code></pre>
  
  <p>In my LoginSuccessHandler : </p>
  
  <pre><code>@Component
  public class RESTLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
  
      private RequestCache requestCache = new HttpSessionRequestCache();
  
      @Override
      public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
              org.springframework.security.core.Authentication authentication) throws IOException, ServletException {
  
          SavedRequest savedRequest = requestCache.getRequest(request, response);
  
          if (savedRequest == null) {
              clearAuthenticationAttributes(request);
              return;
          }
  
          String targetUrlParam = getTargetUrlParameter();
          if (isAlwaysUseDefaultTargetUrl()
                  || (targetUrlParam != null &amp;&amp; StringUtils.hasText(request.getParameter(targetUrlParam)))) {
              requestCache.removeRequest(request, response);
              clearAuthenticationAttributes(request);
              return;
          }
  
          clearAuthenticationAttributes(request);
      }
  
      public void setRequestCache(RequestCache requestCache) {
          this.requestCache = requestCache;
      }
  }
  </code></pre>
  
  <p>So, any idea on what is the problem? Or on how to make an Angular2 app with Spring Boot and Spring Security? Because everything works between Spring Boot and Angular except when I add the security.</p>