📜  decode jwt - TypeScript 代码示例

📅  最后修改于: 2022-03-11 14:48:16.807000             🧑  作者: Mango

代码示例6
import { JwtHelperService } from "@auth0/angular-jwt";

constructor(private jwtHelper: JwtHelperService) {}

// DDECODIFICA TOKEN
CheckUser(): void {
      this.role = this.GetUserRole();
    this.username = this.GetUsername();
    const token = this.tokenGetter();
    if (token && this.jwtHelper.isTokenExpired(token)) {
          alert("Sessione scaduta!");
          this.router.navigate(["login"]);
          return;
    }
    if (token && !this.jwtHelper.isTokenExpired(token)) {
          this.isLogged = true;
          if (this.role === "User") {
            this.adminMode = false;
          } else {
            this.adminMode = true;
          }    
    }
    console.log("logged?: " + this.isLogged);
    console.log("role: " + this.role);
    console.log("username: " + this.username);
    console.log("adminMode?: " + this.adminMode);
}

tokenGetter() {
      return localStorage.getItem("token");
}

GetUserRole() {
    const token = this.tokenGetter();
    if (!token) {
      return;
    }
    let tokenData = this.jwtHelper.decodeToken(token);
    let role =
        tokenData[
          "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
        ];
    return role;
}

GetUsername() {
    const token = this.tokenGetter();
    if (!token) {
      return;
    }
    let tokenData = this.jwtHelper.decodeToken(token);
    let username =
        tokenData[
          "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"
        ];
    return username;
}