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行为。

相关内容

热门资讯

透视软件!wepoker国外版... 透视软件!wepoker国外版透视,we-poker正规吗(都是真的有挂)1、wepoker国外版透...
透视好牌!wepoker辅助器... 透视好牌!wepoker辅助器官方,wepoker怎么挂飞机(本来是有挂)1、任何wepoker怎么...
透视科技!poker辅助器免费... 透视科技!poker辅助器免费安装,wepoker辅助真的假的(其实有挂);1、poker辅助器免费...
透视科技!淘宝买wepoker... 透视科技!淘宝买wepoker透视有用吗,wepoker透视有用吗(切实是有挂)1、超多福利:超高返...
透视脚本!wepoker安装教... 透视脚本!wepoker安装教程,wepokerplus作弊(确实是有挂)1、构建自己的wepoke...
透视辅助!wepoker破解器... 透视辅助!wepoker破解器激活码,wepoker到底有没有透视(果然是有挂)wepoker到底有...
透视规律!wepoker透视苹... 透视规律!wepoker透视苹果系统,we poker辅助器v3.3(一直是有挂);透视规律!wep...
透视计算!wepoker有辅助... 透视计算!wepoker有辅助插件吗,wepoker私人局辅助挂(总是真的是有挂)1、让任何用户在无...
透视了解!wejoker辅助机... 透视了解!wejoker辅助机器人,wepoker到底有没有透视(切实真的有挂);一、wepoker...
透视辅助!wepoker作弊辅... 透视辅助!wepoker作弊辅助,wepoker游戏的安装教程(好像真的有挂)1、超多福利:超高返利...