【问题标题】:Preventing Percent Encoding with URLSearchParams使用 URLSearchParams 防止百分比编码
【发布时间】:2021-11-09 09:36:48
【问题描述】:

我正在尝试使用 Node URL 和 URLSearchParams API 来简化 URL 构建。我正在使用它来构建这样的 URL:

https://<ye olde oauth host>/oauth/authorize?response_type=code&client_id=<my client id>&redirect_uri=https://localhost:4200&scopes=scope1%20scope2

但是,我下面的代码是这样创建 URL 的:

https://<ye olde oauth host>/oauth/authorize?response_type=code&client_id=<my client id>&redirect_uri=https%3A%2F%2Flocalhost%3A4200&scopes=scope1%20scope2

据我了解,URLSearchParams API 将对字符串进行百分比编码,但如果我不希望对它们进行编码,比如 URL,该怎么办?这是我的代码:

const loginURL = new URL('https://<ye olde oauth host>');
    url.pathname = 'oauth/authorize';
    url.search = new URLSearchParams({
      response_type: 'code',
      client_id: '<my client id>'
    }).toString();
loginURL.searchParams.append('redirect_uri', redirectURI);
loginURL.searchParams.append('scopes', scopes);

我不希望对redirect_uri 进行百分比编码的原因是接收端的 OAuth API 不知道如何解析它。有没有办法使用 URLSearchParams 来阻止它编码?

【问题讨论】:

  • loginURL 应该最终转换为字符串吧?如果您在发送之前获得该字符串并再次解码怎么办。
  • 我希望如此,但我打电话给loginURL.href,它以我上面显示的格式给出了 URL,当我调用window.location.href = loginURL.href 时,它仍然有格式不正确的 URL :(

标签: javascript node.js angular typescript oauth


【解决方案1】:

我也遇到过类似的问题。一些百分比符号使我无法发送令牌(无法正确解析令牌)。最后,我只是在发送请求之前使用了decodeURIComponent(url)

【讨论】:

    【解决方案2】:

    the browser spec describes 一样,URL 和 URLSearchParams 在构建 URL 时都会对参数数据进行编码(使用略有不同的编码规则)。

    我知道从 URLSearchParams 中获取未编码的参数值的唯一方法是查找特定的参数值(使用 .get.forEach 或类似方法)。例如:

    const params = new URLSearchParams({
      redirect_uri: 'https://localhost:4200&scopes=scope1 scope2'
    });
    
    params.toString();
    // Returns encoded: 'redirect_uri=https%3A%2F%2Flocalhost%3A4200%26scopes%3Dscope1+scope2'
    
    params.get('redirect_uri');
    // Returns unencoded: 'https://localhost:4200&scopes=scope1 scope2'
    

    您可以使用它来手动构建自己的 url,但这有点违背了这些 API 的目的。

    某些字符只会使 URL 无效,您无法真正绕过对它们进行编码。 Here's some good docs on valid URLs and encodings.

    即使您构造了一个未编码的 URL,当您发出请求时,fetch(和其他类似 fetch 的库)通常也会为您编码。

    从好的方面来说,许多服务器框架希望搜索参数被编码,并在接收到参数时自动解码。如果您的 OAuth 服务还没有这样做,那么它可能应该这样做!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      • 2021-10-10
      • 2013-10-13
      相关资源
      最近更新 更多