gpt4 book ai didi

angular - 安全保护延迟加载模块(Angular 2)

转载 作者:太空狗 更新时间:2023-10-29 17:10:33 25 4
gpt4 key购买 nike

我正在开发一个应用程序,我有一个用户区和一个管理区。我已将它们分成单独的 Angular 2 模块。我已经成功地实现了延迟加载,这样只有在用户请求“/admin”时才能加载管理模块。

从 Angular 2 文档中,我看到我可以像这样指定一个“canLoad”守卫:

  {
path: 'admin',
loadChildren: 'app/admin/admin.module#AdminModule',
canLoad: [AdminGuard]
}

并在 AdminGuard 类中实现一个函数 canLoad,如下所示:

canLoad(route: Route): boolean {
return this.authService.isAdmin();
}

(其中 isAdmin() 可以调用后端 API,这将返回当前用户的 Angular 色或类似的东西)

但这真的会阻止任何非管理员加载 AdminModule 吗?除非我误解了,所有这些代码都位于客户端,那么有什么可以阻止客户端修改“canLoad”方法以使其始终返回 true 吗?像这样:

canLoad(route: Route): boolean {
return true;
}

因此允许客户端加载他们想要的任何模块。

显然,任何需要管理员身份的后端 API 调用都将受到保护,但似乎任何用户都可以查看管理员 UI,这对我来说似乎有点奇怪。有人可以帮我解决这个问题吗?

最佳答案

这是一个很好的问题,我很好奇是否有人对此有详细的答案。所以我发现这个链接进行了非常棒的对话。

Angular 2 Reddit Article

真正让我印象深刻的评论是这个。

Speaking in SPA, generally html templates and your js files will be out in the open for anyone care enough to check. Your SPA will speak to your server in data (read:json) only, the templates will then be populated with this data on client side. so your primary concern is protecting this API. Sessions, cookies, tokens, all are means that still valid here. I myself uses tokens to authenticate and authorize. An API request would contain server signed token, which is then verified and from which roles and credential are extracted, then used to determine that the user is authorized to make that request. Failed check will return 401-unauthorized to the client. On angular side, we save token we received after successful login then use it for subsequent requests. I also decode the credential and roles, and with it display user info and authorize routes. Routes guard in angular is achieved through CanActivate interface, which you can chain multiple of: { Path: 'protected', CanActivate: [LoggedInGuard] },{ Path: 'supersecret', CanActivate: [LoggedInGuard,AdminGuard] } ...etc But client side (read:angular) guards is ultimately UX problem, not a security means. A knowledgeable hacker can just mess with the variables with dev console, or bypass it altogether with straight api call. It's pretty much to show users what error happened and navigate somewhere else etc.

关于angular - 安全保护延迟加载模块(Angular 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42257629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com