我首先使用我编写的身份验证服务中的isLoggedIn
标志跟踪我的登录状态,当用户使用 Identity 在后端成功进行身份验证时,它设置为true
。
现在我想要一种方法来让他们保持登录状态,这样他们在刷新页面时就不必总是登录。我将此功能添加到我的身份验证服务中:
testLogin() : Observable<boolean> {
return this.httpClient.post("/api/Account/TestLogin", null, { observe: "response" })
.map(result => {
if (result.ok) {
this.isLoggedIn = true;
}
return this.isLoggedIn;
});
}
这对我的后端(控制器在属性后面[Authorize]
(:
[HttpPost("[action]")]
public IActionResult TestLogin()
{
return Ok();
}
当我的应用程序启动时,我在app.component.ts
中检查这一点:
constructor(private authService: AuthenticationService) {
authService.testLogin().subscribe(result => {});
}
问题是我的路由防护canActivate
如果isLoggedIn
标志为 true,则返回true
,否则重定向到登录页面并返回false
.这发生在testLogin
函数请求完成之前,因此即使我成功通过身份验证,我也会被重定向到登录,我可以在不登录的情况下从登录页面浏览页面。这是错误的做法吗?我只是使用带有 cookie 的默认 ASP.NET 核心身份设置,但我发现的大多数指南都使用我没有使用的 JWT。
我认为您需要一个服务来保持您的isLoggedIn状态。
.在应用程序启动时设置登录服务.isLoggedIn = false;
.在登录组件上,如果登录正常,则设置 loginService.isLoggedIn = true;
然后使用路由器导航 router.navigate(['home'](;
.在 authGuard 上检查 loginService.isLoggedIn 值。
您还可以在服务中使用函数来设置/获取isLoggedIn值(在这种情况下,该值将是服务的私有值(