В моем проекте у меня есть служба аутентификации , которая связывается с бэкэндом Nodejs и возвращает JWT, сохраненный в пользовательских куки.
export class AuthenticationService {
baseUrl: string = 'xxxxx'
accessToken: string;
userProfile: any;
loggedIn: boolean;
loggedIn$ = new BehaviorSubject<boolean>(this.loggedIn);
loggingIn: boolean;
constructor(private http:HttpClient, private cookie: CookieService, private router: Router) { }
login(username: string, password: string){
console.log(`login invoked`)
return this.http.post<any>(`${this.baseUrl}/users/login`, {email: username, password: password})
.pipe(tap( res => this._getProfile(res),
err => console.log(`Error login: ${err.error.message}`)))
}
private _getProfile(authResult) {
console.log(`_getProfile invoked`)
this.loggingIn = true;
const httpOptions = { headers: new HttpHeaders( {'Authorization': authResult.idToken} ) };
this.http.get(`${this.baseUrl}/users/login`,httpOptions)
.toPromise()
.then(profile => this.setSession(authResult,profile))
.catch((err) => console.warn(`Error retrieving profile: ${err.error.message}`));
}
private setSession(authResult,profile) {
console.log(`setSession invoked`)
let expiredDate = new Date();
expiredDate.setDate( expiredDate.getDate() + 7 );
this.cookie.set('SESSIONID', authResult.idToken,expiredDate,'/');
this.accessToken = authResult.idToken;
this.userProfile = profile;
this.setLoggedIn(true);
this.loggingIn = false;
this.router.navigate(['/'])
}
isAuthenticated() {
return this.cookie.get('SESSIONID') ? true : false;
}
renewToken() {
let token = { idToken: this.cookie.get('SESSIONID')}
this._getProfile(token);
}
setLoggedIn(value: boolean) {
console.log(`actived setLoggedIn ${value}`)
this.loggedIn$.next(value);
this.loggedIn = value;
}
logout(){
console.log('logout clicked')
this.cookie.deleteAll('/');
this.setLoggedIn(false);
}
}
В моем домашнем компоненте я проверяю, сохранен ли токен, и применяю некоторую логику, каждая мысль работает нормально .
load(){
console.log('home - init')
this.auth.isAuthenticated() && this.auth.renewToken();
}
Проблема в форме входа.Я отправляю данные на сервер и корректно проверяю ответ. Он завершает все необходимые процессы в сервисе аутентификации и записывает файлы cookie, но по какой-то причине, когда я пытаюсь получить доступ к переменной loggedIn, все равно false;
login(formData : FormGroup){
this.auth.login(formData.value.email,formData.value.password).subscribe(res =>{
this.toastr.success(`connected`);
},error => this.toastr.error(error.error.message))
}
Вот консольный журнал прогресса.загрузить приложение, выйти из системы, войти в систему, получить доступ к переменной.
введите описание изображения здесь
процесс входа в систему работает нормально, моя проблема заключается в том, что в случае входа в систему из имени входа- не обновлять внутренние переменные auth-сервиса