【发布时间】:2018-02-19 04:45:26
【问题描述】:
我需要帮助来处理我的 Angular 应用程序中的过期令牌。我的 api 已过期,但我的问题是当我忘记退出我的 angular 应用程序时,一段时间后,我仍然可以访问主页但没有数据。我能做些什么吗?有没有可以处理这个的库?或者有什么我可以安装的吗?更好的是,如果我什么都不会安装。下面是我的验证码?我可以添加任何可以处理过期的东西吗?如果它过期了我将无法访问主页。
auth.service.ts
export class AuthService {
private loggedIn = false;
constructor(private httpClient: HttpClient) {
}
signinUser(email: string, password: string) {
const headers = new HttpHeaders()
.set('Content-Type', 'application/json');
return this.httpClient
.post(
'http://sample.com/login',
JSON.stringify({ email, password }),
{ headers: headers }
)
.map(
(response: any) => {
localStorage.setItem('auth_token', response.token);
this.loggedIn = true;
return response;
});
}
isLoggedIn() {
if (localStorage.getItem('auth_token')) {
return this.loggedIn = true;
}
}
logout() {
localStorage.removeItem('auth_token');
this.loggedIn = false;
}
}
authguard.ts
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private authService: AuthService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.authService.isLoggedIn()) {
// logged in so return true
return true;
}
else {
// not logged in so redirect to login page with the return url
this.router.navigate(['signin'])
return false;
}
}
}
【问题讨论】:
-
您可以在离开应用时强制应用清除登录状态。
-
@Pengyy。但我认为这不是专业网络应用程序的工作方式,对吧?关闭浏览器后,他们仍然可以访问自己的帐户。
-
这取决于您应用的身份验证策略。对我来说,奇怪的是应用程序仍然可以登录,但 API 不再可用。
-
注销时发生了什么?
-
@Kuncevic。你的意思是当我点击注销按钮时?它注销了应用程序,我将无法访问主页
标签: angular token access-token angular-http