【问题标题】:How to check if a user is authenticated to acess certain path (MEAN STACK)如何检查用户是否经过身份验证以访问特定路径(MEAN STACK)
【发布时间】:2020-09-28 03:30:53
【问题描述】:

所以我正在学习 MEAN 堆栈,并且我正在尝试进行身份验证,我正在使用本地护照、快速会话、护照猫鼬,我不知道这是你这样做的方式还是有更好的方式,我的节点上有一个 get 来检查用户是否经过身份验证。

exports.isLoggedIn = (req, res) => {
    if (req.isAuthenticated()) {
        res.send(true);
    } else {
        res.send(false);
    }
}

在角度上,我正在以这种方式使用 http 获取身份验证服务

isLoggedIn(): Observable<boolean> {
    return this.httpClient.get<boolean>(this.url + '/isLoggedIn', this.httpOptions).pipe(
      retry(2),
      catchError(this.handleError))
  }

现在我的问题是,当用户尝试访问某个路径时,比如说“/profile”,我想用它来检查用户是否经过身份验证,所以在角度防护中我正在这样做

isLoggedIn: boolean;

canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | boolean {  

    this.auth.isLoggedIn().subscribe((isLoggedIn: boolean) =>  {         
      this.isLoggedIn = isLoggedIn;       
    }); 

    return this.isLoggedIn;

   }  

我认为,我面临的问题是 http 是异步的,而 canActivate 是同步的,所以当我第一次运行它时,我没有定义,第二次返回 true 和 false 为值得关注,但它来自上一次运行,因此如果用户注销,他仍然可以访问“/profile”路径。尝试了一些方法,都失败了,不知道是不是应该这样。

【问题讨论】:

  • 返回 this.auth.isLoggedIn();不要订阅。

标签: javascript node.js angular mean-stack


【解决方案1】:

让我们把你的问题分成两部分

  1. 您还有其他方法,或多或少与护照库的使用相同。所以它已经足够好了,没有什么坏处。

  2. 在前端:

守卫可能会同步返回其布尔值答案。但在许多 在这种情况下,守卫不能同步产生答案。守卫 可以向用户提问,将更改保存到服务器,或获取 新鲜的数据。这些都是异步操作。

因此,路由守卫可以返回 Observable 或 承诺和路由器将等待可观察到 'resolve' 为真或假。

引用自:https://angular.io/guide/router#milestone-5-route-guards

所以考虑到你在组件中的订阅,你需要返回你的 observable,像这样

return this.auth.isLoggedIn()

无需订阅。并且可以选择在您的服务中进行更改以返回布尔值本身。像

isLoggedIn(): Observable < boolean > {
    return this.httpClient.get < boolean > (this.url + '/isLoggedIn', this.httpOptions)
    .pipe(retry(2), tap(val => this.isLoggedIn = true), catchError(this.handleError))
}

更多解决登录服务的方法是参考:https://angular.io/guide/router#resolve-pre-fetching-component-data

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    相关资源
    最近更新 更多