从Web API到Angular客户端,需要验证身份验证令牌

时间:2018-10-23 16:49:38

标签: angular typescript token

我正在学习Angular6。从我的Web api(.net核心),我发送在Postman上看到的以下内容:

{"token":`{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJqeWVlQGNvbGxhYnJhbGluay5jb20iLCJqdGkiOiI2OWVmYmIxNC0wYTBjLTQ5NjgtYjVhZi1mNDYzMTQ2ZDViNmUiLCJ1bmlxdWVfbmFtZSI6IkpvaG5ZZWUiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOlsiYWRtaW4iLCJhbmFseXN0IiwicmV2aWV3ZXIiLCJjb21taXR0ZWUiXSwibmJmIjoxNTQwMzEyODIwLCJleHAiOjE1NDAzMzA4MjAsImlzcyI6ImxvY2FsaG9zdCIsImF1ZCI6InVzZXJzIn0.GegIg2GfpvzI0PGuSIzLUsZtYa-jaGgxGP7yb5A7-CU","expiration":"2018-10-23T21:40:20Z"}`

从我的角度客户端(正在调用网络api),这是我的代码

loginUser(user) : Observable<boolean> {
      var reqHeader = new HttpHeaders({ 'Content-Type': 'application/x-www-urlencoded','No-Auth':'True' });
  return  this.http
        .post('http://localhost:55009/api/login', user )
        .map((data: any) => {
          this.token = data.token;
            localStorage.setItem('userToken', data.token);
            let tokenInfo = this.getDecodedAccessToken(data.token);
console.log('token ===> ' + data.token);
console.log('token ===> ' + tokenInfo);

console.log('token ===> ' + this.token);
                //  this.token = data.token;
                //  this.tokenExpiration = this.getDecodedAccessToken(data.token).ex;
                 this.errorMessage = data.errorMessage;

                //if (this.errorMessage.length > 0) {

               //   alert(data.errorMessage);
              //    return false;
               // }
               // else {
                 // alert(data.errorMessage);

                  return true;
                })
    //  .map((response:any) => response.json())
     .catch(this.handleError);
}



private getDecodedAccessToken(token: string): any {
    try{
        return jwt_decode(token);
    }
    catch(Error){
        return null;
    }
  }

在Chrome控制台上,我只能看到

token ===> [object Object]
login.service.ts:41 token ===> null
login.service.ts:43 token ===> [object Object]

我想验证自己是否获得了有效的令牌,并且能够看到代币的内容和有效期。我安装了jwt-decode,但无法在我的退货中使用。

非常感谢您的帮助。

谢谢

1 个答案:

答案 0 :(得分:0)

通过将响应放在一些json皮棉上,您已经可以看到它是无效的json,但假设它看起来像这样:

{ <- this is where your 'data' start
    "token": { <- this is property of 'data', and it's object
        "token":  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJqeWVlQGNvbGxhYnJhbGluay5jb20iLCJqdGkiOiI2OWVmYmIxNC0wYTBjLTQ5NjgtYjVhZi1mNDYzMTQ2ZDViNmUiLCJ1bmlxdWVfbmFtZSI6IkpvaG5ZZWUiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOlsiYWRtaW4iLCJhbmFseXN0IiwicmV2aWV3ZXIiLCJjb21taXR0ZWUiXSwibmJmIjoxNTQwMzEyODIwLCJleHAiOjE1NDAzMzA4MjAsImlzcyI6ImxvY2FsaG9zdCIsImF1ZCI6InVzZXJzIn0.GegIg2GfpvzI0PGuSIzLUsZtYa-jaGgxGP7yb5A7-CU",
        "expiration": "2018-10-23T21:40:20Z"
    }
}

因此,如果您想获取实际的令牌eyJhbGciOiJIUzI1NiI...,则需要致电data.token.token