2017-10-25 5 views
2

私は、情報を取得するために使用するパラメータを使用することに依存するAngular 4アプリを持っています(つまり、/project/:id/project/1というルートです)。問題はこれが安全ではありません。ユーザーは数字を推測できます。バックエンドで取得するデータの所有者ですAngular idが入っているルートを保護する方法と誰でもそれを推測できますか?

私はバックエンドをチェックしているので、ユーザはproject/310と入力することができ、そのプロジェクトに属していなければデータは返されませんが、ユーザ

私は、セッションストレージを使用してidを保存し、コンポーネントチェックに格納し、リダイレクトしない場合は存在します。

誰かがこれを行うためのより良い/より効率的な方法を持っているなら、私はそれを感謝します。

+0

バージョンを使用していますか? –

+0

角4.残念ですが、私はOPを更新しました – derrickrozay

答えて

2

あなたはルートガードあなたのルーティングに

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を追加する必要があります。

さらに詳しい情報:

CanActivate - 角度のhttps://angular.io/api/router/CanActivate

+0

このようにしたくない理由は、これを行う必要がある約10個のコンポーネントがあるため、10人のガードが必要ですが、 way – derrickrozay

+2

@derrickrozayコンポーネント間でルートガードを再利用できます。複数のルートに 'AuthGuard'を置くだけです。 –

+2

@DerekBrownが正しいです。 とまだ私は私が見る – brijmcq

関連する問題