简体   繁体   English

Angular 2存储承载令牌作为路由传递Param最佳实践

[英]Angular 2 storing bearer Token being passed as a route Param best practice

I have a web app (let's call it app1 ) which is redirecting a user to another app ( app2 ) which leverages angular2. 我有一个网络应用程序(我们称其为app1 ),它将用户重定向到另一个利用angular2的应用程序( app2 )。 A Bearer Token is being passed from app1 to app2 as a route param which will then be stored in local storage and used across app2 . 承载令牌从app1传递到app2作为路由参数,然后将其存储在本地存储中并在app2中使用 At first I added the logic to save the token on app2 in my login.component, but I noticed my login page as flashing for a few seconds while the user was authenticated. 最初,我添加了将令牌保存在我的login.component中的app2上的逻辑,但是我注意到登录页面在验证用户身份时闪烁了几秒钟。 Then I decided to move my logic to my LoginGuard Class which implements CanActivate and looks like this: 然后,我决定将逻辑移至实现CanActivate的 LoginGuard类,如下所示:

canActivate(route:ActivatedRouteSnapshot, state:RouterStateSnapshot) {
    var myToken = route.queryParams['app1Token'] || '';

    if (myToken !== "") {
      localStorage.setItem('app2Token', myToken)

    }

    if (!localStorage.getItem('app2Token')) {
      // not logged in so return true
      return true;
    }

    this.router.navigate(['/home']);
    return false;
}

My question is, what is best practice when it comes to storing a token before the page loads? 我的问题是,在页面加载之前存储令牌时的最佳实践是什么? I've been googling around and I've seen that canActivate should only be used to 'Decide if a route can be activated'. 我一直在搜索,发现canActivate仅应用于“确定是否可以激活路由”。 I also read about Resolve , but I noticed that this is used to fetch data and have it available before the component loads. 我还阅读了有关Resolve的文章 ,但我注意到它用于获取数据并在组件加载之前使数据可用。

This is a good question, I went here to see what they've done in these scenarios: 这是一个好问题,我去这里看看他们在这些情况下做了什么:

https://angular.io/docs/ts/latest/guide/router.html#!#guards https://angular.io/docs/ts/latest/guide/router.html#!#guards

It looks like you're doing pretty much what they recommend -- use the CanActivate to make decisions regarding authentication, and take actions to resolve that if necessary. 看来您正在执行他们所建议的几乎所有工作-使用CanActivate做出有关身份验证的决定,并在必要时采取措施解决该问题。

The only recommendation for improvement would probably be to move your logged-in/localStorage logic into a service and then inject it. 唯一的改进建议可能是将已登录的/ localStorage逻辑移至服务中,然后将其注入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM