我有一个 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
。
更多信息:
关于Angular 如何保护其中有一个 id 并且任何人都可以猜到的路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46922728/