How to generate Cloudinary Authentication signatures in PHP(Laravel)

Viewed 388

I use Cloudinary with Laravel and I want to let users to choose from the existing files or upload new. How can I generate authentication signatures on the BackEnd(php in my case)? and pass it to the front end (JavaScript)?

I've tried to use unsigned upload preset to let users upload without requiring them to be signed in, but no luck.

mediaWidget = cloudinary.createMediaLibrary({
      cloud_name: "my-cloud-name",
      api_key: 'my-api-key',
      username: 'email id',
      uploadPreset: "unsigned-upload-preset",
      multiple: false,
    }, {
      insertHandler: function (data) {
        data.assets.forEach(asset => { console.log("Inserted asset:",
        JSON.stringify(asset, null, 2)) })
        }
      }
    );

I'm getting no error, but it always require user to login into cloudinary account

2 Answers

You can use any SHA-256 hashing function/library to create the signature using the values (cloud name, timestamp, username) mentioned in the documentation. Using PHP as an example, the example in the Media Library documentation looks like this:

<?php

$cloud_name = 'my_company';
$timestamp = '1518601863';
$username= 'jane@mycompany.com';
$api_secret = 'abcd';

$payload_to_sign = 'cloud_name='.$cloud_name.'&timestamp='.$timestamp.'&username='.$username;

$signature = hash('sha256', $payload_to_sign . $api_secret);
print($signature);
?>

This provides the same output as the documentation example: 5cbc5a2a695cbda4fae85de692d446af68b96c6c81db4eb9dd2f63af984fb247

Then, in the Javascript code used to initiate the Media Library widget, you pass the same timestamp, and the signature from the server-side code, and it should open and log you in as the specified user:

window.ml = cloudinary.createMediaLibrary({
    cloud_name: 'my_company',
    api_key: '1234567890',
  username: 'jane@mycompany.com',
  timestamp: '1518601863',
  signature: '5cbc5a2a695cbda4fae85de692d446af68b96c6c81db4eb9dd2f63af984fb247' 
}, function(error, result) {
      console.log(error, result)
});
Related