Integrating AWS Cognito with WordPress

by | May 3, 2024 | 0 comments

At WP Medic, we recently tackled a client project that required integrating AWS Cognito with MemberPress, a popular WordPress membership plugin. In this blog post, we’ll dive into the project requirements and discuss how we used JWT tokens to make authenticated AJAX calls to an AWS API Gateway endpoint to fetch sensitive data from a DynamoDB table.

Technical Requirements

The client needed a robust authentication solution that could scale efficiently and secure sensitive user data. The client had selected AWS Cognito for its powerful user management and authentication features, which we integrated with the MemberPress plugin on the client’s WordPress site. AWS Cognito provides a comprehensive solution for user authentication and management. By using AWS Cognito User Pools, we were able to add a secondary layer of security, ensuring that even if the WordPress site is ever compromised, the sensitive user data remains secure.

Implementing JWT (JSON Web Tokens)

JWT (JSON Web Tokens) play a critical role in secure communications between the client side and the server. For this project, after successful authentication via AWS Cognito, the user’s identity was verified and a JWT was issued. This token was then used in the HTTP header of AJAX calls to authenticate requests sent to AWS API Gateway. This method ensures that only authenticated users could access resources, making the system secure against unauthorized access.

Using JWT for Secure AJAX Calls

Upon login, the JWT was securely stored in the browser’s session storage, ensuring that it was available for subsequent HTTP requests. The AJAX calls included the JWT in the request headers to authenticate and authorize the requests dynamically. If the JWT was valid, AJAX calls were made to AWS API Gateway endpoints, acting as a robust conduit to AWS services like DynamoDB. By securing these endpoints using AWS IAM roles and policies, we ensured that the data fetched from DynamoDB was governed by strict security standards, providing reliable and secure access to database operations.

Example Of An Authenticated AJAX Call

As an example, here is a snippet of the code that has been modified for you to use as an example. This snippet is an example of an authenticated API call, assuming that the user already has been issued an access token.


function handle_fetch_api_data() {
	
    if (empty($_SESSION['aws_cognito_access_token'])) {
        wp_logout();
        wp_redirect('https://website.com/login?message=session_expired');
        exit;
    }

    $accessToken = $_SESSION['aws_cognito_access_token'];

    check_ajax_referer('fetch_api_data_nonce', 'security');

    $apiUrl = "https://api.website.com/endpoint";
    $response = wp_remote_get($apiUrl, array(
        'timeout' => 15,
        'headers' => [
            'Authorization' => 'Bearer ' . $accessToken
        ]
    ));

    if (is_wp_error($response)) {
        error_log('API request failed: ' . $response->get_error_message());
        wp_send_json_error('Unable to retrieve data at this time.');
    } else {
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        if ($data === null) {
            wp_send_json_error('Malformed response from the API.');
        } else {
            wp_send_json_success($data);
        }
    }

    wp_die();
}

add_action('wp_ajax_fetch_api_data', 'handle_fetch_api_data');

DynamoDB Integration

AWS DynamoDB was chosen for its scalability and performance capabilities. It hosted the application data which needed to be retrieved securely through the API Gateway. The integration of DynamoDB with Cognito and API Gateway allowed us to build a highly available, scalable, and secure backend for storing and retrieving data.

Conclusion

Integrating AWS Cognito with MemberPress provided our client with a powerful solution for managing memberships and user authentication. The use of JWT tokens for securing AJAX calls to AWS API Gateway proved to be highly effective in protecting sensitive data transactions. This project not only enhanced the security posture of our client’s website but also streamlined the user experience by ensuring that user interactions were smooth and secure.
This integration showcases the possibilities of leveraging cloud services like AWS Cognito in a WordPress environment, providing insights that can benefit developers looking to enhance their own systems with similar capabilities. We learned a lot about Amazon Web Services in the process and now have the knowledge to make Cognito integrations with other WordPress plugins, be it membership plugins like Thrive Apprentice, Memberful, MembershipWorks, Easy Digital Downloads, WishList Member, or something else entirely.

Need some help?

Let’s discuss your project

Website Development