JSONp authentication for private channels

We’ve released JSONp support for Pusher‘s Javascript client.

JSONp is a way of making cross-domain GET requests from the browser. The Pusher client uses it (optionally) to ask your app for channel authentication when using private and presence channels.

The library still uses Ajax under the hood by default and that works perfectly well when your authentication end-point lives in the same domain as the HTML pages using Pusher. The alternative JSONp authentication is useful for when you want a separate service to act as an authentication provider. Think embeddable widgets.

To use JSONp support, you must use Pusher’s client version 1.6 or above.

Switching to JSONp support is easy. You have to tell Pusher where to find your end-point and switch the default Ajax transport to ‘jsonp’:

<script src="http://js.pusherapp.com/1.6/pusher.min.js"></script><script>// <![CDATA[
Pusher.channel_auth_endpoint = 'http://myserver.com/pusher_jsonp_auth';
  Pusher.channel_auth_transport = 'jsonp';
// ]]></script>

Then you would subscribe to a private or presence channel, as needed.

<script>// <![CDATA[
var pusher = new Pusher('MY_PUSHER_KEY');
  var channel = pusher.subscribe('private-test_channel');

  channel.bind('greet', function(data) {
// ]]></script>

That’s it for the client side. Now you just need to wrap the server’s authentication response in the function name provided in the query string. This parameter is aptly named ‘callback’ and Pusher.js sends it automatically to your JSONp end-point. This is because JSONp works by requiring a remote script that executes a function defined in your local page (Pusher.js defines that function for you).

This is a Rails example of how that end-point would look like.

auth = Pusher['private-test_channel'].authenticate(params[:socket_id], {
  :user_id => current_user.id,
  :user_info => {:name => current_user.name}
render :text => params[:callback] + "(" + auth.to_json + ")"

That’s it. Happy pushing!

P.s. Have you built realtime apps with Pusher? If not, go on, create a free Pusher account and let us know what you think. We’d love to hear from you!

Ready to begin?

Start building your realtime experience today.

From in-app chat to realtime graphs and location tracking, you can rely on Pusher to scale to million of users and trillions of messages