【问题标题】:Angular 2 (4/5) check if user authenticated, best practicesAngular 2 (4/5) 检查用户是否经过身份验证,最佳实践
【发布时间】:2018-03-21 18:51:18
【问题描述】:

我是 Angular 新手,正在为用户实施身份验证。

网络上的大多数建议都建议将会话/用户名保存在本地存储中,当用户返回应用程序时,检查本地存储以显示正确的导航(在我的导航栏中,我有不同的导航按钮用于私人和公共视图)。

但是,我发现这个解决方案有一些缺点。例如,如果服务器上的会话过期,或者手动添加了本地存储,那么当应用程序初始化时,它会在导航栏中显示错误的按钮。

在那之后,我找到了解决方案 - 在显示导航栏按钮之前使用服务,向服务器发送请求以验证本地存储中的用户及其会话当前是否处于活动状态。只有在那之后我才会显示导航按钮。

这里有一个问题:这是证明检查本地存储中的用户是否已登录并且会话是否处于活动状态的最有效方法吗?

还有另一种方法,我正在考虑,但没有找到解决方案。 由于我的角度 webapp 和 nodejs 服务器位于两个不同的位置,当请求 index.html 并使用预渲染的导航栏和响应时,webapp 是否可以检查身份验证状态(从 webapp 服务器向我的 nodejs 服务器发出请求)用户状态(登录或未登录)?

谢谢。

附:我在服务器端使用 PassportJS 和 Express。

【问题讨论】:

标签: node.js angular authentication


【解决方案1】:

最佳实践是使用AuthGuard 并实现CanActivate 来检查用户是否可以查看应用程序的特定部分。通常还使用身份验证服务让用户登录系统并获得访问令牌。

然后,此访问令牌在对服务器的每个请求中用作Authorisation-Header(这是它们将同步的地方)。

您需要在加载时检查JWT/or any other type 令牌,其中包含用户信息和会话超时。

如果令牌无效,您只需将用户重定向到登录,否则它将允许用户去他们想去的地方。

一个实际的例子可以在here找到。

【讨论】:

    【解决方案2】:

    要让导航栏为经过身份验证和未经过身份验证的用户显示不同的元素,可能的解决方案之一是

    1. authentication.service.ts中使用一些“/auth-check”请求,每次发生当前用户授权检查结果的事件时都会触发

    ...

    interface ShareObj {   [id: string]: any; }
    

    ...

    currentUserId: ShareObj = {};
    currentUserUsername: ShareObj = {};
    

    public authenticatedBehavior = new ReplaySubject(1);

    authCheck(): any {
        return this.http.get('/api/auth-check')
          .map((resp: any) => {
            if (resp.authanticated) {
                this.currentUserId['global'] = resp.user.id;
                this.currentUserUsername['global'] = resp.user.username;
                this.authenticatedBehavior.next(true);
            } else {
                this.authenticatedBehavior.next(false);
                this.currentUserId['global'] = null;
                this.currentUserUsername['global'] = null;
            }
    
            return resp;
          })
          .catch(e => {
            this.authenticatedBehavior.next(false);
            this.currentUserId['global'] = null;
            this.currentUserUsername['global'] = null;
          });
      }
    

    所以,在navbar.component.ts 中应该有一个监听这个事件:

    ngOnInit() {
        this.authService.authenticatedBehavior
          .subscribe(
            data => {
              // do change of UI of navbar depending if user logged in or not
            }
          );
      }
    
    1. 拥有error-iterceptor.ts 文件,您应该在其中“捕获”所有失败的请求并检查它们是否有Unauthorised 响应(401)。如果您收到此类响应,请在authentication.service.ts 中执行authCheck() 以确保当前用户的会话已过期并通知所有侦听authenticatedBehavior 的组件

    【讨论】:

      猜你喜欢
      • 2015-05-23
      • 1970-01-01
      • 1970-01-01
      • 2017-09-03
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      • 2016-06-07
      相关资源
      最近更新 更多