Skip to content

Signed Cookies with ip does not work

0

I'm trying to make a signed cookies with an IPv4 in my policy on aws cloudfront, but it doesn't work, I don't have access to the resources from this IPv4. You can check my function php.

public function generateSignedCookie($cloudFrontClient, $resourceKey, $expires, $ip=null){
        
        $keyPairId = env('AWS_CLOUDFRONT_KEY_PAIR_ID');
        $privateKey = env('AWS_CLOUDFRONT_CERTIFICAT_PATH');
        $expires = time() + $expires;
        $policy ='{"Statement":[{"Resource":"'. $resourceKey . '","Condition":{"DateLessThan":{"AWS:EpochTime":' . $expires . '}}}]}';
        if(!is_null($ip)){
            $ip .= '/32';
            app('log')->info('Generate cookies for IP: ' . $ip);
            $policy ='{"Statement":[{"Resource":"'. $resourceKey . '","Condition":{"IpAddress":{"AWS:SourceIp":"' . $ip . '"},"DateLessThan":{"AWS:EpochTime":' . $expires . '}}}]}';
        }
        app('log')->info('Creating cookies with policy ' . $policy);
        try {
            $result = $cloudFrontClient->getSignedCookie([
                'policy' => $policy,
                'private_key' => $privateKey,
                'key_pair_id' => $keyPairId
            ]);
            app('log')->info('Signed Cookie generated : ' . json_encode($result));
            return $result;
        }
        catch (AwsException $e) {
            return ['Error' => $e->getAwsErrorMessage()];
        }
    }

Thanks.

asked 2 years ago206 views
1 Answer
0

Hi,

You may want to read this blog post that provides detailled guidance (and code) to implement signed cookies: https://dev.to/muhammad_ahmad_khan/distributing-restricted-static-content-through-cloudfront-using-signed-cookies-20hp

Best,

Didier

EXPERT
answered 2 years ago
EXPERT
reviewed 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.