Как сохранить сессию входа в Spring Boot - PullRequest
0 голосов
/ 01 июля 2019

Я пытаюсь сохранить логин пользователя после обновления страницы, и вот мой код: login.service.ts

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 });
  }
}

И login.component.ts :

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 => {
        console.log("res = " + res);
        localStorage.setItem("xAuthToken", res.json().token);
        this.loggedIn = true;
        // location.reload();
      },
      error => {
        console.log("error = " + error);
      }
    );
  }

  ngOnInit() {
    this.loginService.checkSession().subscribe(
      res => {
        console.log("Good")
        this.loggedIn = true;
      },
      error => {
        console.log("Bad")
        this.loggedIn = false;
      }
    );
  }

И в LoginResource.java :

@RequestMapping("/checkSession")
public ResponseEntity<String> checkSession() {
    return new ResponseEntity<String>("Session Active!", HttpStatus.OK);
}

Но я получил ошибку:

GET http://localhost:8181/checkSession 401 zone-evergreen.js: 2952

Но у меня проблема только с checkSession() в ** login.service.ts ** и ngOnInit() в ** login.component.ts **, в строке this.loginService.checkSession().subscribe(.

Если я удалю эти функции, все ошибки исчезнут, но мне придется входить в систему каждый раз при обновлении страницы.

Spring Config:

@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());
    }

}

Журнална сервере (после добавления console.log):

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.<computed> @ 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

и ответ об ошибке:

{"timestamp":"2019-07-02T02:13:37.300+0000","status":401,"error":"Unauthorized","message":"Unauthorized","path":"/checkSession"}

Что я не знаю, как это исправить.Кто-нибудь знает, как это сделать?

1 Ответ

0 голосов
/ 02 июля 2019

Решенная проблема:

LoginService

checkSession() {
    const url = 'http://localhost:8181/checkSession';
    const xToken = localStorage.getItem('xAuthToken');
    const basicHeader = 'Basic ' + localStorage.getItem('credentials');
    const headers = new Headers({
      'x-auth-token' : xToken,
      'Authorization' : basicHeader
    });
    console.log(url);
    console.log(headers);
    return this.http.get(url, {headers: headers});
  }

LoginComponent

onSubmit() {
    this.loginService
      .sendCredential(this.credential.username, this.credential.password)
      .subscribe(
        res => {
          localStorage.setItem('xAuthToken', res.json().token);
          this.loggedIn = true;
          const encodedCredentials = btoa(this.credential.username + ':' + this.credential.password);
          localStorage.setItem('credentials', encodedCredentials);
          // location.reload();
        },
        error => {
          console.log(error);
        }
      );
  }

** ngOnInit **

  ngOnInit() {
    const xToken = localStorage.getItem('xAuthToken');
    if (xToken) {
      this.loginService.checkSession().subscribe(
        res => {
          console.log("Good")
          this.loggedIn = true;
        },
        error => {
          console.log("error = " + error)
          this.loggedIn = false;
        }
      );
    }
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...