【问题标题】:Angular 7+ how to prevent query params special characters to be converted to hexcode?Angular 7+ 如何防止查询参数特殊字符转换为十六进制代码?
【发布时间】:2020-08-25 13:56:11
【问题描述】:

示例端点:

https://localhost:4200/test/index.html?param1=username%2passw0rd&baseApi=https://someOtherService/APIBase.jsp?INT/

当我点击上面的端点时。我的网址被转换成这个...

https://localhost:4200/test/index.html?param1=username%2passw0rd&baseApi=https:%2F%2FsomeOtherService%2FAPIBase.jsp

正如您在 baseApi 参数中看到的那样,“/”被转换为“%2F”,并且值“?INT/”也被删除了。

如何防止 URL 转换“/”并为第二个参数“baseApi”中的值保留“?INT/”值。

Reference

【问题讨论】:

  • 我的问题是为什么你需要首先停止编码。

标签: angular


【解决方案1】:

你没有。如果允许,它将破坏互联网。

更多细节:

  1. 您可以使用后端 API 上的 URL 解码将 URL 转换回标准文本。
  2. 永远不要在 URL 中传递密码。这实际上是您可以做的最不安全的事情之一。

关于第 1 点:情况并非总是如此,许多 API 框架会自动解码查询字符串。

如果您需要传递完整的 URL,请确保正确编码:

console.log("https://localhost:4200/test/index.html?" + encodeURIComponent("param1=username%2passw0rd&baseApi=https://someOtherService/APIBase.jsp?INT/"));

https://localhost:4200/test/index.html?param1%3Dusername%252passw0rd%26baseApi%3Dhttps%3A%2F%2FsomeOtherService%2FAPIBase.jsp%3FINT%2F

【讨论】:

  • 如果 1. 不可能,我可以做一个解决方法。但是#2呢?当我单击端点时,param2 查询参数“?PRD/”在加载时消失。我使用了您提供的 console.log 并得到了与您分享的完全相同的响应。
  • ?PRD 对 URI 进行编码应该在重定向时保留它。我们是在谈论重定向丢弃它吗?此外,#2 是关于密码的。假设 API 使用类似 POST 而不是 get,并且不会在 POST 参数中对其进行编码。
  • 刷新时 ?INT/ 消失
【解决方案2】:

您不能也不应该试图阻止特殊字符被转换。正确的方法是在发送用户之前故意对其进行编码,然后在读取数据之前对其进行解码。如果您使用的是 javascript,那么您可以通过 encodeURIComponent(string)decodeURIComponent(string) 执行此操作。

encodeURIComponent() 将接受任何字符串,并将其转换为 URL 友好格式。

decodeURIComponent() 将采用转换后的字符串,并将其改回常规格式。

至于原因为什么你不应该试图阻止它们被转换.....我将在这里引用 Mozilla:

For example, if a user writes "Jack & Jill", using encodeURIComponent the text will get encoded as "Jack %26 Jill". Without encoding, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data.

换句话说,假设您在 URL 中允许使用符号,并且有人创建了一个名为“Jack&baseApi=evilURL”的用户名。你的网址最终会是

http://localhost:4200?username=Jack&baseApi=evilURL&baseApi=https://someOtherService

我不想站在你的服务器上,试图猜测正确的 baseApi 是“evilURL”还是“someOtherService”。

【讨论】:

  • 您能解释一下为什么“?INT/”在加载时会在 url 中消失
猜你喜欢
  • 2012-07-08
  • 2013-04-03
  • 1970-01-01
  • 2014-09-28
  • 1970-01-01
  • 2018-07-12
  • 2014-03-19
相关资源
最近更新 更多