在 Angular 应用程序中,我试图保留用户的logged_in属性,直到他使用localStorage. 虽然数据是加密保存的localStorage,但我们可以在用户注销后手动复制数据并粘贴进去,那么这里的安全性就被破坏了(我们将能够访问应用程序而无需仅使用加密密钥登录)。我们怎样才能实现这个功能?如果用户关闭所有选项卡,则用户退出是可以的。而不是使用localStorage// SessionStorage,Cookie我们怎样才能做到这一点?实现这一点的最佳方法是什么?
2 回答
0
由于使用 cookie 似乎存在中等漏洞,因此我使用了带有编码数据的 cookie。
于 2019-12-17T08:18:25.967 回答
0
解决此问题的一种方法是将 JWT 存储在本地存储中。因此,在启动应用程序时(通过访问 url)触发服务方法将 JWT 令牌发送到后端并对其进行验证。如果验证成功,则继续正常流程,否则清除本地存储并导航到登录页面。
执行此操作的最佳位置是 app.component 的 ngOnInit。此外,JWT 可以有过期时间,因此在规定的时间(最好是可以配置的一个小时)之后,令牌就会失效。这样做可以避免任何其他用户使用相同的凭证。在 app.component.ts
...
export class AppComponent implements onInit{
constructor(private authService: AuthService){
}
ngOnInit(){
this.authService.authenticate()
}
}
在 AuthService 中
...
export class AuthService{
token: string;
constructor(private http: HttpClient,private router: Router){
}
authenticate(){
this.token = localStorage.get("JWT");
this.http.post<any>("YOUR_BACKEND",{token: this.token})
.subscribe((data)=>{
//do nothing
},
(err)=>{
this.router.navigate(["/login"]);
localstorage.removeItem("JWT")
})
}
...
}
于 2019-11-15T11:49:59.833 回答