在Perl Mojolicious中渲染JSON时,请防止逃生角色

发布于 2025-01-21 08:55:28 字数 580 浏览 1 评论 0 原文

我有一个莫约利奇的控制器,该控制器调用

$controller->render_to_string(json => { %{$hashref} });
# or
$controller->render_to_string(json => $hashref);

$ hashref 包含写入JSON对象时被逃脱的字符。
例如:

my $hashref = {
  path => '/path/to/file'
}

输出哪个是:

{
  "path": "\\/path\\/to\\/file"
}

有没有办法通知 render_to_string()方法不插入/逃脱这些值?

我应该提到实际的字符串是MD5哈希。

I have a Mojolicious controller that calls

$controller->render_to_string(json => { %{$hashref} });
# or
$controller->render_to_string(json => $hashref);

The $hashref contains characters that are being escaped when written to the JSON object.
For example:

my $hashref = {
  path => '/path/to/file'
}

Which are being output as:

{
  "path": "\\/path\\/to\\/file"
}

Is there a way to inform the render_to_string() method not to interpolate/escape these values?

I should mention that the actual strings are MD5 hashes.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泪是无色的血 2025-01-28 08:55:28

当渲染JSON时,Mojolicious Escapes /字符以防止。这在

字符/将始终逃脱以防止XSS攻击。

 “</script>” - > “< \/script>”
 

实际上,这是通过>完成的 Mojo :: JSON 本身,反对“这是由每次渲染JSON内容自动完成的”。这意味着1)当您执行 - > Render(json => ...)和2)修复程序仅使用另一个JSON模块时,没有干净的方法来防止此行为进行编码,并指定格式=> 'json'在调用 Render (这会导致响应的标题包含 content-type:application/json ,如 mojolicious :: guides :: guides :: guendering :: Rendering ):

use JSON qw( encode_json );

$controller->render(text => encode_json($hashref), format => 'json');

如果您只想将 $ controller-> render_to_string 渲染到字符串(就像您在问题中所做的那样),则可以省略 form> format => 'json'(无论如何,格式 render_to_string ):

use JSON qw( encode_json );

my $json = $controller->render_to_string(text => encode_json($hashref));

When rendering JSON, Mojolicious escapes / characters to prevent XSS attacks. This is mentioned in the documentation of Mojo::JSON:

The character / will always be escaped to prevent XSS attacks.

"</script>" -> "<\/script>"

In practice, this is done by Mojo::JSON itself, by opposition to "this is done by Mojolicious automatically every time it renders JSON content". This means that 1) there is no clean way to prevent this behavior when you do ->render( json => ... ), and 2) the fix is simply to use another JSON module to do the encoding, and specify format => 'json' in the call to render (which will cause the headers of the response to contain Content-Type: application/json, as explained in Mojolicious::Guides::Rendering):

use JSON qw( encode_json );

$controller->render(text => encode_json($hashref), format => 'json');

If you just want to render to a string with $controller->render_to_string (as you've done in your question), then you can omit format => 'json' (anyways, format is ignored by render_to_string):

use JSON qw( encode_json );

my $json = $controller->render_to_string(text => encode_json($hashref));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文