Angular 如何保护一条有id的路线,任何人都能猜到?
我有一个Angular 4应用程序,它依赖于使用参数来获取信息(也就是说,路由是Angular 如何保护一条有id的路线,任何人都能猜到?,angular,Angular,我有一个Angular 4应用程序,它依赖于使用参数来获取信息(也就是说,路由是/project/:id/project/1问题是,这并不安全,因为任何用户都可以猜到号码。我在后端验证请求它的人是所检索数据的所有者,以防发生意外 由于我在后端检查,用户仍然可以输入project/310,如果该项目不属于他们,则不会返回任何数据,但用户仍将看到HTML页面 我考虑过使用会话存储来存储id,然后在组件检查中查看它是否存在(如果没有重定向) 如果有人能找到更好/更有效的方法,我将不胜感激。您需要一名路
/project/:id
/project/1
问题是,这并不安全,因为任何用户都可以猜到号码。我在后端验证请求它的人是所检索数据的所有者,以防发生意外
由于我在后端检查,用户仍然可以输入project/310
,如果该项目不属于他们,则不会返回任何数据,但用户仍将看到HTML页面
我考虑过使用会话存储来存储id
,然后在组件检查中查看它是否存在(如果没有重定向)
如果有人能找到更好/更有效的方法,我将不胜感激。您需要一名路线守卫
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-您使用的是哪个版本的angular?angular 4.抱歉,我已经更新了OPS。我不想这样做的原因是因为我有大约10个组件,我必须这样做,所以我需要10个不同的防护装置,但我没有看到任何其他防护装置way@derrickrozay您可以跨组件重用路由保护。只需放置
AuthGuard
在多个路由中。@DerekBrown是正确的。假设您有productdetailscomponent,您可以执行以下操作{path:'productdetails/:id',component:productdetailscomponent,canActivate:[AuthGuard]}但仍然使用我回答的同一个authguard。唯一的问题是,如果我有10条路由,我将不得不在每一条路由上调用我的API,以检查它们是否是相同的owner@derrickrozay一开始,它可能看起来是多余的,但如果您只检查一次,请考虑一下。如果您对数据库做了一些更改,比如您想删除Privilege o如果你真的想要这种安全性,我认为每次检查都是很好的。或者改变auth-guard不调用api,而是在其他地方调用它,比如从另一个服务调用api一次。