Angular 如何保护其中有一个 id 并且任何人都可以猜到的路由?

标签 angular

我有一个 Angular 4 应用程序,它依赖于使用我用来获取信息的参数(即 /project/:id /project/1问题是这不安全,因为任何用户都可以猜出号码。我通过在后端验证请求它的人是正在检索的数据的所有者来采取预防措施。

由于我正在检查后端,用户仍然可以输入 project/310,如果该项目不属于他们,则不会返回任何数据,但用户仍会看到 HTML 页面。

我考虑过使用 session 存储来存储 id,然后在组件中检查并查看它是否存在(如果不重定向)。

如果有人有更好/更有效的方法来做到这一点,我将不胜感激。

最佳答案

你需要一个Route Guard

import { AngularFireAuth } from 'angularfire2/auth';
import { Injectable } from '@angular/core';
import { Router,  ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
  loggedIn = false;

  constructor(private dummyService: DummyService, private router: Router) {
  }
  canActivate( route: ActivatedRouteSnapshot,  state: RouterStateSnapshot) {
   //To get the data in the url for instance,'product/1'
   const productId = route.params.id; 
   //here get the data and do the necessary logic
  return this.dummyService.SomeFunction
      .map( authState => !!authState) need to return a boolean
      .do( auth => {
            //user is not the owner of the data so redirect them somewhere else
          if (!auth) {
            this.router.navigate(['/login']);
          }
            //if you got here, then the user is the owner of the data.
      }).take(1);
      }
    }

在你的路由中,添加这个

  {
    path: 'product/:id',
    component: SomeComponent,
    canActivate: [AuthGuard ]
  }

并在 app.module 的提供者中添加 AuthGuard

更多信息:

可以激活 - https://angular.io/api/router/CanActivate

关于Angular 如何保护其中有一个 id 并且任何人都可以猜到的路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46922728/

相关文章:

angular2模板绑定(bind)unicode

angular - 为什么导入 OnInit 很重要

angular - 停止点击的指令不工作 Angular 2

html - HTML 中的属性和特性有什么区别?

Angular CLI - 检测库更改以重建消费应用程序

Angular 5 Component - 我如何获得内容中的所有输入

angular - 我什么时候应该使用 TS 在 Angular 2+ 中导入类型?

angular - 每个表格行的 react 形式

angular - RxJs:在 subscribe() 中使用 try/catch 是否正确?

node.js - Npm链接在Angular7项目中不起作用