Tag: php


Using Credentials from AWS Security Token Service

by Jeremy Lindblom | on | in PHP | Permalink | Comments |  Share

A recent post on the AWS PHP Development forum inspired me to write a quick post about how to use credentials vended by AWS Security Token Service with the AWS SDK for PHP.

What is AWS Security Token Service?

AWS Security Token Service (AWS STS) is a web service that enables you to request temporary, limited-privilege AWS credentials for AWS Identity and Access Management (AWS IAM) users or for users that you authenticate via identity federation. One common use case for using temporary credentials is to grant mobile or client-side applications access to AWS resources by authenticating users through third-party identity providers (read more about Web Identity Federation).

Getting Temporary Credentials

AWS STS has five operations that return temporary credentials: AssumeRole, AssumeRoleWithWebIdentity, AssumeRoleWithSAML (recently added), GetFederationToken, and GetSessionToken. Using the GetSessionToken operation is easy, so let’s use that one as an example. Assuming you have an instance of AwsStsStsClient stored in the $sts variable, this is how you call the method:

$result = $sts->getSessionToken();

See? I told you it was easy. The result for GetSessionToken and the other AWS STS operations always contains a 'Credentials' value. If you print the result (e.g., print_r($result)), it looks like the following:

Array
(
    ...
    [Credentials] => Array
    (
        [SessionToken] => '<base64 encoded session token value>'
        [SecretAccessKey] => '<temporary secret access key value>'
        [Expiration] => 2013-11-01T01:57:52Z
        [AccessKeyId] => '<temporary access key value>'
    )
    ...
)

Using Temporary Credentials

You can use temporary credentials with another AWS client by instantiating the client and passing in the values received from AWS STS directly.

use AwsS3S3Client;

$result = $sts->getSessionToken();

$s3 = S3Client::factory(array(
    'key'    => $result['Credentials']['AccessKeyId'],
    'secret' => $result['Credentials']['SecretAccessKey'],
    'token'  => $result['Credentials']['SessionToken'],
));

You can also construct a Credentials object and use that when instantiating the client.

use AwsCommonCredentialsCredentials;
use AwsS3S3Client;

$result = $sts->getSessionToken();

$credentials = new Credentials(
    $result['Credentials']['AccessKeyId'],
    $result['Credentials']['SecretAccessKey'],
    $result['Credentials']['SessionToken']
);

$s3 = S3Client::factory(array('credentials' => $credentials));

However, the best way to provide temporary credentials is to use the createCredentials() helper method included with StsClient. This method extracts the data from an AWS STS result and creates the Credentials object for you.

$result = $sts->getSessionToken();
$credentials = $sts->createCredentials($result);

$s3 = S3Client::factory(array('credentials' => $credentials));

You can also use the same technique when setting credentials on an existing client object.

$credentials = $sts->createCredentials($sts->getSessionToken());
$s3->setCredentials($credentials);

Closing Notes

For information about why you might need to use temporary credentials in your application or project, see Scenarios for Granting Temporary Access in the AWS STS documentation.

If you would like to read more about providing credentials to the SDK, check out one of our other blog posts: Providing Credentials to the AWS SDK for PHP.

AWS re:Invent Slides Posted

by Jeremy Lindblom | on | in PHP | Permalink | Comments |  Share

AWS re:Invent was an amazing event this year. We are glad that we could connect with the PHP developers that were there.

If you weren’t there, be sure to watch the Day 1 Keynote with AWS Sr. Vice President Andy Jassy and Day 2 Keynote with Amazon CTO, Werner Vogels. Well known AWS customers like Netflix shared their experiences, and there were a few new services announced, including AWS CloudTrail, Amazon Kinesis, Amazon Workspaces, and Amazon AppStream. AWS CloudTrail support is available in the AWS SDK for PHP as of Version 2.4.10.

We want to let you know that the slides for our presentation, Mastering the AWS SDK for PHP are now available on SlideShare. You can find the slides for all of the AWS re:Invent presentations here.

We’ll share more about AWS re:Invent with you, including the video of our presentation, during the next few weeks.

AWS Service Provider for Silex – Version 1.1.0

by Jeremy Lindblom | on | in PHP | Permalink | Comments |  Share

We would like to announce the availability of version 1.1.0
of the AWS Service Provider for Silex. This release updates the package’s
dependencies to work with the latest versions of the AWS SDK for PHP and
Silex.

Let us know what you think! Please submit any issues or feature requests to our GitHub issue
tracker
.

Release: AWS SDK for PHP – Version 2.4.10

by Jeremy Lindblom | on | in PHP | Permalink | Comments |  Share

We would like to announce the release of version 2.4.10 of the AWS SDK for PHP. This release adds support for AWS CloudTrail, identity federation using SAML 2.0 for AWS Identity and Access Management (IAM), and a few new features to the Amazon Redshift client.

Changelog

  • Added support for AWS CloudTrail
  • Added support for identity federation using SAML 2.0 to the AWS STS client
  • Added support for configuring SAML-compliant identity providers to the AWS IAM client
  • Added support for HSM storage for encryption keys to the Amazon Redshift client
  • Added support for encryption key rotation to the Amazon Redshift client
  • Added support for database audit logging to the Amazon Redshift client

Install/Download the Latest SDK

See You at AWS re:Invent 2013

by Jeremy Lindblom | on | in PHP | Permalink | Comments |  Share

AWS re:Invent is next week (November 12th-15th) in Las Vegas! We are excited to be there and to have an opportunity to talk to you in person.

There is going to be a lot of great technical content year. Michael Dowling and I will be presenting a session on Friday called Mastering the AWS SDK for PHP. We will also be hanging out in the developer lounge area, so come by any time, especially during our PHP development office hours.

Last year Michael and I spoke as well. In case you missed it, our presentation was called Using Amazon DynamoDB Effectively with the AWS SDK for PHP. We also have the slides for that presentation posted on Slideshare. We’ll be sure to post the slides and video for this year’s presentation as well after the conference.

See you there!

Release: AWS SDK for PHP – Version 2.4.9

by Michael Dowling | on | in PHP | Permalink | Comments |  Share

We would like to announce the release of version 2.4.9 of the AWS SDK for PHP. This release adds support for cross zone load balancing in Elastic Load Balancing, stack policies in AWS CloudFormation, and the Gateway-Virtual Tape Library in AWS Storage Gateway.

Changelog

  • Added support for cross-zone load balancing to the Elastic Load Balancing client.
  • Added support for a new gateway configuration, Gateway-Virtual Tape Library, to the AWS Storage Gateway client.
  • Added support for stack policies to the the AWS CloudFormation client.
  • Fixed issue #176 where attempting to upload a direct to Amazon S3 using the UploadBuilder failed when using a custom iterator that needs to be rewound.

Install/Download the Latest SDK

AWS at ZendCon 2013

by Jeremy Lindblom | on | in PHP | Permalink | Comments |  Share

Recently, the AWS SDK for PHP team attended ZendCon, the largest conference in the U.S. that focuses on PHP development. AWS was a sponsor for ZendCon this year, so the entire PHP SDK team was able to attend. It was great to be able to talk to our customers and get feedback from those who have used AWS and our SDK. We want you to know that we are thankful for your feedback and that we’ve shared it all with various teams at AWS.

What You Heard About AWS at the Conference

It was apparent to everyone at ZendCon this year that "The Cloud" was a very hot topic. There were also many speakers that spoke about or mentioned AWS in their sessions and keynotes. I will call attention to a few of these in case you want to look back and read the slides or watch the videos.

Integrating Zend and AWS

Zend is the company that hosts ZendCon, and has helped manage the development of the PHP language since PHP 3. They also create commercial PHP products and services like Zend Studio and Zend Server. Though there are several ways in which Zend products and services integrate with AWS, I want to specifically call out two of them:

  1. Zend Server on AWS Marketplace – If you are a Zend Server user and an AWS customer, you can easily launch Zend Server on Amazon EC2 through AWS Marketplace.
  2. AWS SDK Module for Zend Framework – If you write PHP applications with Zend Framework 2, you can use the AWS SDK ZF2 Module to easily integrate the AWS SDK for PHP into your application. To learn about how to install and use the module, see the AWS SDK ZF2 Module README.

Until Next Year…

We enjoyed being at ZendCon and connecting with you. We also hope that you were able to learn more about AWS while you were there, or if you couldn’t make it, through the presentation slides afterward. If you need any help using the AWS SDK for PHP or have any feedback for us, be sure to connect with us via the PHP SDK forum or our GitHub repo.

Providing credentials to the AWS SDK for PHP

by Michael Dowling | on | in PHP | Permalink | Comments |  Share

In order to authenticate requests, the AWS SDK for PHP requires credentials in the form of an AWS access key ID and secret access key. In this post, we’ll discuss how to configure credentials in the AWS SDK for SDK.

Configuring credentials

There are several methods that can be used for configuring credentials in the SDK. The method that you use to supply credentials to your application is up to you, but we recommend that you use IAM roles when running on Amazon EC2 or use environment variables when running elsewhere.

Credentials can be specified in several ways:

  1. IAM roles (Amazon EC2 only)
  2. Environment variables
  3. Configuration file and the service builder
  4. Passing credentials into a client factory method

If you do not provide credentials to the SDK using a factory method or a service builder configuration file, the SDK checks if the AWS_ACCESS_KEY_ID and AWS_SECRET_KEY environment variables are present. If defined, these values are used as your credentials. If these environment variables are not found, the SDK attempts to retrieve IAM role credentials from an Amazon EC2 instance metadata server. If your application is running on Amazon EC2 and the instance metadata server responds successfully with credentials, they are used to authenticate requests. If none of the above methods successfully yield credentials, an AwsCommonExceptionInstanceProfileCredentialsException exception is thrown.

IAM roles (Amazon EC2 only)

IAM roles are the preferred method for providing credentials to applications running on Amazon EC2. IAM roles remove the need to worry about credential management from your application. They allow an instance to "assume" a role by retrieving temporary credentials from the instance’s metadata server. These temporary credentials allow access to the actions and resources that the role’s policy allows.

When launching an EC2 instance, you can choose to associate it with an IAM role. Any application running on that EC2 instance is then allowed to assume the associated role. Amazon EC2 handles all the legwork of securely authenticating instances to the IAM service to assume the role and periodically refreshing the retrieved role credentials, keeping your application secure with almost no work on your part.

If you do not provide credentials and no environment variable credentials available, the SDK attempts to retrieve IAM role credentials from an Amazon EC2 instance metadata server. These credentials are available only when running on Amazon EC2 instances that have been configured with an IAM role.

Caching IAM role credentials

While using IAM role credentials is the preferred method for providing credentials to an application running on an Amazon EC2 instance, the roundtrip from the application to the instance metadata server on each request can introduce latency. In these situations, you might find that utilizing a caching layer on top of your IAM role credentials can eliminate the introduced latency.

The easiest way to add a cache to your IAM role credentials is to specify a credentials cache using the credentials.cache option in a client’s factory method or in a service builder configuration file. The credentials.cache configuration setting should be set to an object that implements Guzzle’s GuzzleCacheCacheAdapterInterface. This interface provides an abstraction layer over various cache backends, including Doctrine Cache, Zend Framework 2 cache, etc.

<?php

require 'vendor/autoload.php';

use DoctrineCommonCacheFilesystemCache;
use GuzzleCacheDoctrineCacheAdapter;

// Create a cache adapter that stores data on the filesystem
$cacheAdapter = new DoctrineCacheAdapter(new FilesystemCache('/tmp/cache'));

// Provide a credentials.cache to cache credentials to the file system
$s3 = AwsS3S3Client::factory(array(
    'credentials.cache' => $cacheAdapter
));

With the addition of credentials.cache, credentials are now cached to the local filesystem using Doctrine’s caching system. Every request that uses this cache adapter first checks if the credentials are in the cache. If the credentials are found in the cache, the client then ensures that the credentials are not expired. In the event that cached credentials become expired, the client automatically refreshes the credentials on the next request and populates the cache with the updated credentials.

A credentials cache can also be used in a service builder configuration:

<?php

// File saved as /path/to/custom/config.php

use DoctrineCommonCacheFilesystemCache;
use GuzzleCacheDoctrineCacheAdapter;

$cacheAdapter = new DoctrineCacheAdapter(new FilesystemCache('/tmp/cache'));

return array(
    'includes' => array('_aws'),
    'services' => array(
        'default_settings' => array(
            'params' => array(
                'credentials.cache' => $cacheAdapter
            )
        )
    )
);

If you were to use the above configuration file with a service builder, then all of the clients created through the service builder would utilize a shared credentials cache object.

Environment variables

If you do not provide credentials to a client’s factory method or via a service builder configuration, the SDK attempts to find credentials in your environment by checking in the $_SERVER superglobal and using the getenv() function, looking for the AWS_ACCESS_KEY_ID and AWS_SECRET_KEY environment variables.

If you are hosting your application on AWS Elastic Beanstalk, you can set the AWS_ACCESS_KEY_ID and AWS_SECRET_KEY environment variables through the AWS Elastic Beanstalk console so that the SDK can use those credentials automatically.

Configuration file and the service builder

The SDK provides a service builder that can be used to share configuration values across multiple clients. The service builder allows you to specify default configuration values (e.g., credentials and regions) that are applied to every client. The service builder is configured using either JSON configuration files or PHP scripts that return an array.

Here’s an example of a configuration script that returns an array of configuration data that can be used by the service builder:

<?php

// File saved as /path/to/custom/config.php

return array(
    // Bootstrap the configuration file with AWS specific features
    'includes' => array('_aws'),
    'services' => array(
        // All AWS clients extend from 'default_settings'. Here we are
        // overriding 'default_settings' with our default credentials and
        // providing a default region setting.
        'default_settings' => array(
            'params' => array(
                'key'    => 'your-aws-access-key-id',
                'secret' => 'your-aws-secret-access-key',
                'region' => 'us-west-1'
            )
        )
    )
);

After creating and saving the configuration file, you need to instantiate a service builder.

<?php

// Assuming the SDK was installed via Composer
require 'vendor/autoload.php';

use AwsCommonAws;

// Create the AWS service builder, providing the path to the config file
$aws = Aws::factory('/path/to/custom/config.php');

At this point, you can now create clients using the get() method of the Aws object:

$s3 = $aws->get('s3');

Passing credentials into a factory method

A simple way to specify your credentials is by injecting them directly into the factory method of a client. This is useful for quick scripting, but be careful to not hard-code your credentials inside of your applications. Hard-coding your credentials inside of an application can be dangerous because it is easy to commit your credentials into an SCM repository, potentially exposing your credentials to more people than intended. It can also make it difficult to rotate credentials in the future.

<?php

$s3 = AwsS3S3Client::factory(array(
    'key'    => 'my-access-key-id',
    'secret' => 'my-secret-access-key'
));

New Twitter Account for the AWS SDK for PHP

by Jeremy Lindblom | on | in PHP | Permalink | Comments |  Share

Last week, we opened up a new Twitter account to run in parallel with this blog. You can find us there at
@awsforphp. We will tweet about new posts on the blog, tips and tricks for
using the SDK, new releases, and upcoming conferences and events that we’ll be attending.

Be sure to follow us to keep up-to-date. :-)

Release: AWS SDK for PHP – Version 2.4.8

by Michael Dowling | on | in PHP | Permalink | Comments |  Share

We would like to announce the release of version 2.4.8 of the AWS SDK for PHP. This release updates the AWS Direct Connect client and updates the Amazon Elastic MapReduce client to add support for new EMR APIs, termination of specific cluster instances, and unlimited EMR steps.

Changelog

  • Updated the AWS Direct Connect client
  • Updated the Amazon Elastic MapReduce client to add support for new EMR APIs, termination of specific cluster instances, and unlimited EMR steps.

Install/Download the Latest SDK