2

我正在使用 auth gaurd 来防止我的 Angular 应用程序中的 URL 操作并将 URL 操作重定向到登录页面。但这会导致问题,即使在成功登录后,刷新网页时也会将其视为 URL 操作,并通过重定向到登录页面将用户注销。请注意,我没有使用 JWT 或任何类似的身份验证机制. 这是基于后端数据库返回的密码的普通身份验证。到目前为止,我还没有维护任何会话。下面我附上了我已将路径映射到路线的片段:

const appRoutes: Routes = [
  { path: '', component: LoginComponent },
  { path: 'dashboard', canActivate: [AuthGuard], component: DashboardComponent },
  { path: 'file-uploader', canActivate: [AuthGuard], component: FileUploaderComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'login', component: LoginComponent }
 ];


@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private user: UserService, private router: Router) {}
  canActivate() {
    if (this.user.getUserLoggedIn()) {
          return true;
    }
    else
      return false;
  }
}

请帮我解决这个问题。在此先感谢。

4

1 回答 1

0

可能有点晚了,但我遇到了同样的问题并通过使用 sessionStorage 解决了它。只要您的浏览器选项卡打开,它就可以存储值并保留它们。当用户第一次访问您的页面时,sessionStorage 中没有设置任何值,因此 authGuard 返回 false 并将用户重定向到登录页面。成功登录后,将 sessionStorage 中的userLoggedIn值设置为 true,如下所示:

sessionStorage.setItem('userLoggedIn', 'true')

在您的 AuthGuard 中,您现在可以从 sessionStorage 中获取userLoggedIn值。由于setItem方法只接受字符串,因此您必须像这样解析它:

const isAuthenticated = JSON.parse(sessionStorage.getItem('userLoggedIn')

这会将字符串转换为正确的布尔值格式。然后在您的 authGuard 中,您可以检查 isAuthenticated。当用户注销或应该自动注销时,您只需更新 sessionStorage 值

sessionStorage.setItem('userLoggedIn', 'false')
于 2021-01-11T12:13:55.027 回答