What is JSON with padding?

status
Published
date
Nov 27, 2022
featured_image
slug
what-is-json-with-padding
tags
summary
What is exactly JSONP? What it looks like and why it threats web client security? How it could be handled dynamically?
type
Post
JSONP (JSON with padding) is a tricky way to send cross-site GET requests by getting around the browser’s same-origin policy. The modern browsers follow the CORS rules when sending XHR (XMLHttpRequest) requests, but JSONP bypasses it due to the way how it sends requests.
JSONP isn’t an XHR request; it’s a script load on the page but returns a function call. This is what JSONP data looks like:
But, what does it do exactly?
Let’s assume your web page has functions from the app.js file that loads on the page with script tags. As the page opens, the script tag will send a request for the app.js and loads it, the definition of functions will be processed onto the page, and the functions will be ready to call. This is how JavaScript files are processed.
But, if you put an endpoint URL into the script tag with a callback parameter, the server would return only a JSONP object ready-to-call on the client if the returning function is defined on the client right after the page resolves the script tag.

Dynamic JSONP requests

Instead of sending the requests when the page initiates, requests can be sent dynamically by injecting a script element into the DOM within a function.

Is it safe?

Well, no. It’s just a basic hack to make cross-domain requests, and sites that use JSONP services are prone to CSRF; well, that’s why XHR request methods have CORS policies: to keep safe client users.
An attack that prepared for potential XSS vulnerabilities, such as stealing user cookies, can also be demonstrated for JSONP. The provider of JSONP data must be trustable and ensure that it doesn’t return any malicious JavaScript code and try to run a different callback than given.

Conclusion

JSONP is an old-fashioned and hacky way, but not safe, to send GET requests to the client. XHR requests, such as ajax and fetch, are restricted to sending cross-site requests, but it is still possible to send with JSONP.
Plus, it is not that useful to use it in JavaScript applications due to no callback functions are provided to handle potential errors, even though some libraries like jQuery and Angular implemented a native way to send JSONP requests.
There is no need to use it.

© Samet 2017 - 2024