从路由中安全地检索值

Safely retrieving a value from a route

在我的 Angular 应用程序中,我更新了我项目中的一些 URL,因为之前使用的查询字符串元素如下:

http://www.whatever.com/products?productName=TheMainProduct&id=234234

到类似这样的基于路由的系统:

http://www.whatever.com/products/TheMainProduct/234234

这很好用,但大多数情况下,除非有一个名为 The / Next / Big Thing 的产品

所以斜线如预期的那样破坏了路由。我已经使用 encodeUrlComponent 对产品名称进行了编码,并打算使用 decodeUrlComponent 进行解码,但我很好奇这是否被认为是安全的。这些值将与它们是查询字符串元素时的值相同并且被认为是安全的,所以 decodeUrlComponent 可以在这里使用还是我应该添加额外的保护层以防止恶意角度?

我阅读了关于 decodeUrlComponent 是否是好的做法的不同报告,所以如果它不是一个好主意,我正在寻找一些明确的或替代方案。

为什么需要解码?好吧,我正在导航到一个组件并使用取自 URL 的产品名称来填充我导航到的组件上的一些数据。因此,例如,表单字段将在其中预填充产品名称,因为它取自 URL.

原评论

Oh. then I think best solution here is to use URL object to create a url and decode it using decodeUrlComponent as you mentioned. If I have access to the backend code, I would validate the title on the server and add constraint to the database to prevent unwanted characters on the title. If I don't have access to the backend, then encoding and decoding is the only solution for me

在这种情况下,我将使用 JavaScript 的 URL object 从产品标题创建编码 url。

const product_url = new URL('The / Next / Big Thing', 'http://www.whatever.com/products')

这将 return 编码 URL 用于 Angular 路由器。

当涉及到恶意代码时,我会做的是防止将它们插入到数据库中。这意味着,每当创建产品时,检查服务器上是否存在可疑字符,如 </> 等,并防止它们插入。

我建议你使用这个 library,它可以解码由 encodeURIencodeURIComponent 编码的字符串,而不会在无效转义时抛出错误