title: Angular5 - Set cookies returned from spring form login
body: <p>I am trying to add spring security to an app which is build using angular5 and spring boot 1.5.8. The authentication mechanism I am trying to add is spring boot's formLogin.</p>
  
  <p>I am authenticating the user through rest call, and not through default form action. The login works fine but the subsequent rest calls fails. I am making this rest calls with cookies 'ON' so that it will send cookies to spring app, but still the request fails. The reason is angular doesn't set response cookies returned from authentication.</p>
  
  <p>Set cookies in auth.service.ts's login method once rest is successfull.</p>
  
  <p>How to make angular set the cookies returned from spring security please help....</p>
  
  <p>Here is the code:</p>
  
  <p><strong>login.component.html</strong></p>
  
  <pre><code>&lt;form name="form-signin" (ngSubmit)="login()" #f="ngForm" novalidate&gt;
    &lt;div class="form-group" &gt;
      &lt;label for="username"&gt;Username&lt;/label&gt;
      &lt;input type="text" class="form-control" id="username" name="username" [(ngModel)]="user.username" /&gt;
    &lt;/div&gt;
    &lt;div class="form-group"&gt;
      &lt;label for="password"&gt;Password&lt;/label&gt;
      &lt;input type="password" class="form-control" id="password" name="password" [(ngModel)]="user.password" /&gt;        
    &lt;/div&gt;
    &lt;/div&gt;
    &lt;button class="btn btn-lg btn-primary btn-block btn-signin" type="submit"&gt;Sign in&lt;/button&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p><strong>login.component.ts</strong></p>
  
  <pre><code>export class LoginComponent implements OnInit {
    user: User=new User();
    constructor(private authService :AuthService, private router: Router) { }
  
    ngOnInit() {
    }
  
    login(){
      this.authService.logIn(this.user).subscribe(data=&gt;{
              this.authService.testRest().subscribe(data=&gt;{
              this.router.navigate(['/dashboard']);
              });
          },err=&gt;{
              this.errorMessage="error :  Username or password is incorrect";
          }
        )
    }
  }
  </code></pre>
  
  <p><strong>auth.service.ts</strong></p>
  
  <pre><code>export class AuthService {
    constructor(public http: HttpClient) { }
  
    public logIn(user: User){
      const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/x-www-form-urlencoded'
      })
      };
      let body = new URLSearchParams();
      body.set('username', user.username);
      body.set('password', user.password);
  
      return this.http.post(AppComponent.API_URL+"/login" , body.toString() ,  httpOptions)
        .map((response: Response) =&gt; {
       //How to make angular set cookies here
        console.log(JSON.stringify(response));
      });
    }
  
    testRest() {
      return this.http.get(AppComponent.API_URL+"/testRest", { withCredentials: true }) .map((response: Response) =&gt; {
        console.log(JSON.stringify(response));
      });
    }
  }
  </code></pre>
  
  <p><strong>WebConfig.java</strong></p>
  
  <pre><code>@Configurable
  @EnableWebSecurity
  public class WebConfig extends WebSecurityConfigurerAdapter {
  
      @Autowired
      private AppUserDetailsService appUserDetailsService;
      @Autowired
      private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
      @Autowired
      private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
  
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.inMemoryAuthentication()
                  .withUser("user")
                  .password("password")
                  .roles("USER");
      }
  
      @Bean
      public WebMvcConfigurer corsConfigurer() {
          return new WebMvcConfigurerAdapter() {
              @Override
              public void addCorsMappings(CorsRegistry registry) {
                  registry.addMapping("/**").allowedOrigins("http://localhost:4200");
  
              }
          };
      }
  
      @Override
      public void configure(WebSecurity web) throws Exception {
          super.configure(web);
      }
  
    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http.cors()
          .and()
          .authorizeRequests()
          .antMatchers("/login")
          .permitAll()
          .anyRequest()
          .fullyAuthenticated()
          .and()
          .logout()
          .permitAll()
          .logoutRequestMatcher(new AntPathRequestMatcher("/logout", "POST"))
          .and()
         .formLogin().successHandler(customAuthenticationSuccessHandler).failureHandler(customAuthenticationFailureHandler)
          .and()
          .sessionManagement()
          .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
          .and()
          .csrf()
          .disable();
      }
  }
  </code></pre>
  
  <p><strong>TestController.java</strong></p>
  
  <pre><code>public class TestController {
  
      @CrossOrigin
      @RequestMapping("/testRest")
      public String testRest() {
          Map&lt;String, String&gt; test= new HashMap&lt;&gt;();
          test.put("key", "Test Value");
          return test;
      }
  }
  </code></pre>
  
  <p><strong>pom.xml</strong></p>
  
  <pre><code>&lt;parent&gt;
          &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
          &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
          &lt;version&gt;1.5.8.RELEASE&lt;/version&gt;
          &lt;relativePath/&gt; 
      &lt;/parent&gt;
  &lt;dependencies&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
              &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
              &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
              &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.springframework.session&lt;/groupId&gt;
              &lt;artifactId&gt;spring-session&lt;/artifactId&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
              &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt;
              &lt;scope&gt;runtime&lt;/scope&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;com.h2database&lt;/groupId&gt;
              &lt;artifactId&gt;h2&lt;/artifactId&gt;
              &lt;version&gt;1.4.196&lt;/version&gt;
          &lt;/dependency&gt;
  &lt;/dependencies&gt;
  </code></pre>