title: How to keep Login Session in Spring Boot
body: <p>I try to keep user login after refreshing page, and here is my code:
  <strong>login.service.ts</strong></p>
  
  <pre><code>import { Injectable } from '@angular/core';
  import { Http, Headers } from '@angular/http';
  
  @Injectable({
    providedIn: 'root'
  })
  export class LoginService {
  
    constructor(private http: Http) {
    }
  
    sendCredential(username: string, password: string) {
      let url = "http://localhost:8181/token";
      let encodedCredentials = btoa(username + ":" + password);
      let basicHeader = "Basic " + encodedCredentials;
      let headers = new Headers({
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': basicHeader
      })
      return this.http.get(url, { headers: headers });
    }
  
    checkSession() {
      let url = "http://localhost:8181/checkSession";
      console.log("localStorage.getItem('xAuthToken') = " + localStorage.getItem('xAuthToken'));
      let headers = new Headers({
        'x-auth-token': localStorage.getItem('xAuthToken')
      });
  
      return this.http.get(url, { headers: headers });
    }
  }
  </code></pre>
  
  <p>And <strong>login.component.ts</strong>:</p>
  
  <pre><code>export class LoginComponent implements OnInit {
  
    private credential = { 'username': '', 'password': '' };
    private loggedIn = false;
  
    constructor(private loginService: LoginService) { }
    onSubmit() {
    console.log("this.loginService.checkSession() = " + JSON.stringify(this.loginService.checkSession()));
      this.loginService.sendCredential(this.credential.username, this.credential.password).subscribe(
        res =&gt; {
          console.log("res = " + res);
          localStorage.setItem("xAuthToken", res.json().token);
          this.loggedIn = true;
          // location.reload();
        },
        error =&gt; {
          console.log("error = " + error);
        }
      );
    }
  
    ngOnInit() {
      this.loginService.checkSession().subscribe(
        res =&gt; {
          console.log("Good")
          this.loggedIn = true;
        },
        error =&gt; {
          console.log("Bad")
          this.loggedIn = false;
        }
      );
    }
  </code></pre>
  
  <p>And in <strong>LoginResource.java</strong>:</p>
  
  <pre><code>@RequestMapping("/checkSession")
  public ResponseEntity&lt;String&gt; checkSession() {
      return new ResponseEntity&lt;String&gt;("Session Active!", HttpStatus.OK);
  }
  </code></pre>
  
  <p>But I got error: </p>
  
  <blockquote>
    <p>GET <a href="http://localhost:8181/checkSession" rel="nofollow noreferrer">http://localhost:8181/checkSession</a> 401 zone-evergreen.js:2952 </p>
  </blockquote>
  
  <p>But I only get problem with <code>checkSession()</code> in ** login.service.ts** and <code>ngOnInit()</code> in ** login.component.ts**, at line <code>this.loginService.checkSession().subscribe(</code>. </p>
  
  <p>If I delete these function, all error will be gone, but I have to login again each time I refresh the page.</p>
  
  <p>Spring Config:</p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
      @Autowired
      private Environment environment;
  
      @Autowired
      private UserSecurityService userSecurityService;
  
      private BCryptPasswordEncoder passwordEncoder() {
          return SecurityUtility.passwordEncoder();
      }
  
      private static final String[] PUBLIC_MATCHERS = { "/css/**", "/js/**", "/image/**", "/book/**", "/user/**" };
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
  
          http
  //          .csrf().disable().cors().disable()
                  .httpBasic().and().authorizeRequests().antMatchers(PUBLIC_MATCHERS).permitAll().anyRequest()
                  .authenticated();
      }
  
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
          auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
      }
  
  }
  </code></pre>
  
  <p>Log on Server(after add some console.log):</p>
  
  <pre><code>Angular is running in the development mode. Call enableProdMode() to enable the production mode.
  login.service.ts:30 localStorage.getItem('xAuthToken') = 35cf03fc-eeec-4dac-b187-1adb61ac31e9
  login.component.ts:35 this.loginService.checkSession() = {"_isScalar":false}
  login.service.ts:30 localStorage.getItem('xAuthToken') = 35cf03fc-eeec-4dac-b187-1adb61ac31e9
  zone-evergreen.js:2952 GET http://localhost:8181/checkSession 401
  scheduleTask @ zone-evergreen.js:2952
  scheduleTask @ zone-evergreen.js:378
  onScheduleTask @ zone-evergreen.js:272
  scheduleTask @ zone-evergreen.js:372
  scheduleTask @ zone-evergreen.js:211
  scheduleMacroTask @ zone-evergreen.js:234
  scheduleMacroTaskWithCurrentZone @ zone-evergreen.js:1107
  (anonymous) @ zone-evergreen.js:2985
  proto.&lt;computed&gt; @ zone-evergreen.js:1428
  (anonymous) @ http.js:1314
  _trySubscribe @ Observable.js:42
  subscribe @ Observable.js:28
  ngOnInit @ login.component.ts:36
  checkAndUpdateDirectiveInline @ core.js:24503
  checkAndUpdateNodeInline @ core.js:35163
  checkAndUpdateNode @ core.js:35102
  debugCheckAndUpdateNode @ core.js:36124
  debugCheckDirectivesFn @ core.js:36067
  (anonymous) @ LoginComponent_Host.ngfactory.js? [sm]:1
  debugUpdateDirectives @ core.js:36055
  checkAndUpdateView @ core.js:35067
  callViewAction @ core.js:35433
  execEmbeddedViewsAction @ core.js:35390
  checkAndUpdateView @ core.js:35068
  callViewAction @ core.js:35433
  execComponentViewsAction @ core.js:35361
  checkAndUpdateView @ core.js:35074
  callWithDebugContext @ core.js:36407
  debugCheckAndUpdateView @ core.js:35990
  detectChanges @ core.js:23807
  tick @ core.js:32079
  (anonymous) @ core.js:31927
  invoke @ zone-evergreen.js:359
  onInvoke @ core.js:30904
  invoke @ zone-evergreen.js:358
  run @ zone-evergreen.js:124
  run @ core.js:30769
  next @ core.js:31924
  schedulerFn @ core.js:27846
  __tryOrUnsub @ Subscriber.js:185
  next @ Subscriber.js:124
  _next @ Subscriber.js:72
  next @ Subscriber.js:49
  next @ Subject.js:39
  emit @ core.js:27808
  checkStable @ core.js:30847
  onHasTask @ core.js:30924
  hasTask @ zone-evergreen.js:411
  _updateTaskCount @ zone-evergreen.js:431
  _updateTaskCount @ zone-evergreen.js:264
  runTask @ zone-evergreen.js:185
  drainMicroTaskQueue @ zone-evergreen.js:559
  Promise.then (async)
  scheduleMicroTask @ zone-evergreen.js:542
  scheduleTask @ zone-evergreen.js:381
  scheduleTask @ zone-evergreen.js:211
  scheduleMicroTask @ zone-evergreen.js:231
  scheduleResolveOrReject @ zone-evergreen.js:845
  then @ zone-evergreen.js:955
  bootstrapModule @ core.js:31656
  ./src/main.ts @ main.ts:11
  __webpack_require__ @ bootstrap:78
  0 @ main.ts:12
  __webpack_require__ @ bootstrap:78
  checkDeferredModules @ bootstrap:45
  webpackJsonpCallback @ bootstrap:32
  (anonymous) @ main.js:1
  Show 22 more frames
  login.component.ts:42 error = Response with status: 401 OK for URL: http://localhost:8181/checkSession
  </code></pre>
  
  <p>And Error Response: </p>
  
  <pre><code>{"timestamp":"2019-07-02T02:13:37.300+0000","status":401,"error":"Unauthorized","message":"Unauthorized","path":"/checkSession"}
  </code></pre>
  
  <p>Which I don't know how to fix it. Anyone know how to do that?</p>