登录,解析token,登出

121 阅读1分钟
export class ClaimTypes {
  public static claimsName: string = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name";
  public static claimsNameIdentifier: string = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier";
  // public static deptID: string = "Dept";
  public static givenName: string = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname";
}

登录用到的类

export class ClaimsPrincipal {
  constructor() {
    this.userID = 0;
    this.username = "";
    this.deptID = 0;
    this.givenName = "";
  }

  public userID: number;
  public username: string;
  public deptID: number;
  public givenName: string;
}

登录方法

//传入请求回来的token
public signIn(token: string): void {
    if (!token) {
      throw "token不存在";
    }
    //储存到浏览器内存,备用
    window.sessionStorage.setItem("token", token);
    //正则全局替换-为+,_为/,这样可以解析token
    const payload = JSON.parse(
      decodeURIComponent(
        escape(
          //atob() 方法用于解码使用 base-64 编码的字符串。
          window.atob(
            token
              .split(".")[1]
              .replace(/-/g, "+")
              .replace(/_/g, "/")
          )
        )
      )
    );
    //储存一些解析出来的值
    let principal = new ClaimsPrincipal();
    principal.userID = payload[ClaimTypes.claimsNameIdentifier];
    principal.username = payload[ClaimTypes.claimsName];
    // principal.deptID = payload[ClaimTypes.deptID];
    principal.givenName = payload[ClaimTypes.givenName];
    //储存账号昵称
    window.sessionStorage.setItem("givenName", principal.givenName);
    Vue.prototype.$user = principal;
  }

储存

    let principal = new ClaimsPrincipal();
    principal.userID = payload[ClaimTypes.claimsNameIdentifier];
    principal.username = payload[ClaimTypes.claimsName];
    // principal.deptID = payload[ClaimTypes.deptID];
    principal.givenName = payload[ClaimTypes.givenName];
    Vue.prototype.$user = principal;

登出

public signOut(): void {
    //清除token和账号昵称
    window.sessionStorage.removeItem("token");
    window.sessionStorage.removeItem("givenName");
    Vue.prototype.$user = AuthenticationManager.defaultPrincipal;
  }