角度安全问题 - 身份验证

问题描述 投票:0回答:1
angular spring authentication security
1个回答
0
投票

您遇到的错误消息“无法读取 null 的属性(读取“用户名”)”表明代码正在尝试访问 null 或未定义的对象的“用户名”属性。在您的代码中,当您尝试访问 this.responseAll 对象的“用户名”属性时,似乎会发生这种情况。

要解决此问题,您应该在尝试访问其属性之前检查 this.responseAll 对象是否为 null 或未定义。您可以通过添加条件检查来做到这一点。

这是代码的更新版本,其中包含条件检查以防止错误:

验证(凭证:任何,回调:任何){ 常量标头 = 新的 HttpHeaders( 证书 ? { '内容类型':'应用程序/json', 授权: '基本' + btoa(凭证.用户名 + ':' + 凭证.密码), } :{} ); this.str = JSON.stringify(标题); // this.str = JSON.stringify(headers, null, 4); //(可选)漂亮的缩进输出。 console.log(this.str); // 将输出记录到开发工具控制台。 this.httpClient.get(environment.apiBaseUrl + '登录/用户', { headers: headers }).subscribe((response) => { this.responseAll = 响应; console.log("connexion=" + this.responseAll);

if (this.responseAll && this.responseAll['username']) {
  this.authenticated = true;
  console.log("true or false=" + this.authenticated);
  console.log("username=" + this.responseAll['username']);
  for (let i = 0; i < this.responseAll['roles'].length; i++) {
    console.log("id====" + this.responseAll['roles'][i]['idRole']);
    if (this.responseAll['roles'][i]['idRole'] == 1) {
      this.isAdmin = true;
    }
  }
} else {
  this.authenticated = false;
}

return callback && callback();

}); }

© www.soinside.com 2019 - 2024. All rights reserved.