Angular使用oAuth2-oidc:检查用户是否先前已注销
创始人
2024-10-29 13:00:41
0

可以通过在AuthService中添加一个名为“isLoggedIn”的公共方法来检查用户是否已经注销。此方法将返回一个Observable,该Observable将返回一个布尔值,指示用户的当前身份验证状态。 以下是一个示例AuthService,其中包含一个isLoggedIn方法:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, BehaviorSubject } from 'rxjs';
import { tap } from 'rxjs/operators';
import { JwtHelperService } from '@auth0/angular-jwt';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  private loggedIn = new BehaviorSubject(false);

  get isLoggedIn() {
    return this.loggedIn.asObservable(); // 使用asObservable()方法使loggedIn变为只读
  }

  constructor(private http: HttpClient, public jwtHelper: JwtHelperService) { }

  login(username: string, password: string): Observable {
    // 登录逻辑
  }

  logout() {
    // 注销逻辑
    this.loggedIn.next(false); // 在注销时将loggedIn设置为false
  }

  isAuthenticated(): boolean {
    const token = localStorage.getItem('access_token');
    return !this.jwtHelper.isTokenExpired(token);
  }

  checkTokenValidity(): Observable {
    const token = localStorage.getItem('access_token');
    return this.http.get(`${environment.apiBaseUrl}/auth/check-token-validity?token=${token}`)
    .pipe(
      tap(() => {
        this.loggedIn.next(true); // 在令牌有效且未注销时将loggedIn设置为true
      }, () => {
        this.loggedIn.next(false); // 在令牌无效时将loggedIn设置为false
      })
    );
  }

}

在AppComponent中,我们可以使用AuthService的isLoggedIn方法来确定用户是否已注销:

import { Component, OnInit } from '@angular/core';
import { AuthService } from './services/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  title = 'my-app';
  isLoggedIn: boolean;

  constructor(private authService: AuthService) {}

  ngOnInit(): void {
    this.authService.isLoggedIn.subscribe((loggedIn) => {
      this.isLoggedIn = loggedIn;
    });
  }

}

在此示例中,我们订阅AuthService的isLoggedIn可观察对象,并在检测到身份验证状态更改时更新isLoggedIn属性。此属性可以在组件中用于显示/隐藏元素或更改用户Interface行为。

相关内容

热门资讯

透视线上"wepok... 1、透视线上"wepoker买钻石有用吗"详细辅助分享教程(透视苹果系统技巧)2、进入游戏-大厅左侧...
透视游戏"德州局透视... 您好,德州局透视脚本免费版下载手机版这款游戏可以开挂的,确实是有挂的,需要了解加微【13670430...
透视有挂"德州局怎么... 透视有挂"德州局怎么透视"详细辅助切实教程(可以获得好牌方法)准备好在德州局怎么透视 ia的高塔上攀...
透视中牌率"约局吧透... 1、透视中牌率"约局吧透视挂下载"详细辅助必赢教程(有机器人透明);详细教程。2、约局吧透视挂下载透...
透视数据"hhpok... 透视数据"hhpoker外挂靠谱吗"详细辅助专业教程(有透视功能技巧)是由北京得hhpoker外挂靠...
辅助透视"wepok... 辅助透视"wepoker可以免费玩吗"详细辅助安装教程(透视脚本免费下载pc软件);1.wepoke...
透视免费"大菠萝免费... 透视免费"大菠萝免费辅助"详细辅助2025新版教程(透视脚本苹果版技巧)是一款可以让一直输的玩家,快...
透视透视"hh po... 透视透视"hh poker辅助器先试用"详细辅助必赢教程(透视底牌攻略),支持语音通讯、好友开房及战...
透视新版"werpl... 透视新版"werplan有挂吗"详细辅助介绍教程(透视脚本免费软件)是由北京得werplan有挂吗黑...
透视挂"wepoke... 透视挂"wepoker辅助软件视频"详细辅助微扑克教程(透视辅助下载技巧);建议优先通过wepoke...