<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Rushi Patel</title>
    <description>The latest articles on DEV Community by Rushi Patel (@xushiii).</description>
    <link>https://dev.to/xushiii</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1088524%2F09a43855-fb05-431e-8179-ba98581ac3b9.jpg</url>
      <title>DEV Community: Rushi Patel</title>
      <link>https://dev.to/xushiii</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/xushiii"/>
    <language>en</language>
    <item>
      <title>Mastering Dynamic Response Streaming Lambda with AWS Bedrock and TypeScript</title>
      <dc:creator>Rushi Patel</dc:creator>
      <pubDate>Wed, 22 Nov 2023 20:33:46 +0000</pubDate>
      <link>https://dev.to/xushiii/mastering-dynamic-response-streaming-lambda-with-aws-bedrock-and-typescript-2ch1</link>
      <guid>https://dev.to/xushiii/mastering-dynamic-response-streaming-lambda-with-aws-bedrock-and-typescript-2ch1</guid>
      <description>&lt;p&gt;In the dynamic landscape of serverless architecture, where efficiency and real-time responsiveness reign supreme, the concept of response streaming emerges as a pivotal player. Unlike traditional request-response models, response streaming allows for the incremental transmission of data, enabling a continuous flow of information from the server to the client.&lt;/p&gt;

&lt;p&gt;Imagine a scenario where large datasets need to be processed and delivered to end-users in real-time, or where updates to a client application should be instantaneously reflected. Response streaming transforms the serverless paradigm by facilitating the progressive delivery of results, enhancing user experience, and optimizing resource utilization.&lt;/p&gt;

&lt;p&gt;In this comprehensive guide, we’ll walk you through the intricacies of setting up AWS Bedrock with AWS CDK, crafting a TypeScript Lambda function for response streaming, and seamlessly integrating it all with AWS CDK. By the end of this journey, you’ll be well-equipped to enhance your serverless applications with unparalleled efficiency and responsiveness.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Setup Bedrock with AWS CDK
&lt;/h2&gt;

&lt;p&gt;Check out my previous blog on “&lt;a href="https://medium.com/aws-tip/unleashing-the-power-of-generative-ai-with-aws-bedrock-aws-cdk-typescript-e85af50d0559" rel="noopener noreferrer"&gt;Unleashing the Power of Generative AI with AWS Bedrock, AWS CDK, TypeScript&lt;/a&gt;” for a comprehensive guide on setting up Bedrock with AWS CDK.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example Lambda for Leveraging Response Streaming
&lt;/h2&gt;

&lt;p&gt;Lambda response streaming allows your functions to send back a response in chunks, enabling real-time updates and more efficient handling of large datasets. This feature is especially powerful in scenarios where immediate and incremental processing of data is crucial.&lt;/p&gt;

&lt;p&gt;Let’s dive into a TypeScript example that showcases the power of response streaming&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {
  BedrockRuntimeClient,
  InvokeModelWithResponseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";

import { streamifyResponse } from "lambda-stream";

import * as stream from 'stream';
import * as util from 'util';

const { Readable } = stream;
const pipeline = util.promisify(stream.pipeline);

function parseBase64(message: string) {
  return JSON.parse(Buffer.from(message, "base64").toString("utf-8"));
}

const client = new BedrockRuntimeClient({
  region: "us-west-2",
});

export const handler = streamifyResponse(
  async (event, responseStream, _context) =&amp;gt; {

    const prompt = 'Can you please what is Pure Function in React?'

    const claudPrompt = `Human: Human:${prompt} Assistant:`;

    const params = {
      modelId: "anthropic.claude-v2",
      contentType: "application/json",
      accept: "*/*",
      body: `{"prompt":"${claudPrompt}","max_tokens_to_sample":2048,"temperature":0.5,"top_k":250,"top_p":0.5,"stop_sequences":[], "anthropic_version":"bedrock-2023-05-31"}`,
    };

    console.log(params);

    const command = new InvokeModelWithResponseStreamCommand(params);

    const response: any = await client.send(command);
    const chunks = [];

    for await (const chunk of response.body) {
      const parsed = parseBase64(chunk.chunk.bytes);
      chunks.push(parsed.completion);
      responseStream.write(parsed.completion);
    }

    console.log(chunks.join(""));
    responseStream.end();
  }
);
export default handler;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How to Configure Lambda Function URL as Response Stream in AWS CDK
&lt;/h2&gt;

&lt;p&gt;Now that we have a TypeScript Lambda function capable of response streaming, the next step is to seamlessly integrate it with AWS CDK. This integration allows for better management and deployment of the serverless infrastructure.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const bedrockResponseStreamingLambda = new aws_lambda_nodejs.NodejsFunction(
      this,
      "BedrockResponseStreamingLambda",
      {
        runtime: aws_lambda.Runtime.NODEJS_16_X,
        handler: "handler",
        entry: path.join(__dirname, "../src/lambda/bedrock-repsone-streaming/index.ts"),
        bundling: {
          forceDockerBundling: false,
          nodeModules:['lambda-stream']
        },
        timeout: Duration.seconds(90),
      }
    );

const lambdaUrl = bedrockResponseStreamingLambda.addFunctionUrl({
      authType: aws_lambda.FunctionUrlAuthType.NONE,
      invokeMode: aws_lambda.InvokeMode.RESPONSE_STREAM
    });

new CfnOutput(this,'LambdaEndpoint',{
      value:lambdaUrl.url
    })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Testing the Configured Lambda Function
&lt;/h2&gt;

&lt;p&gt;Before diving into testing, ensure you’ve deployed your infrastructure by running the cdk deploy command in your terminal.&lt;/p&gt;

&lt;p&gt;To make testing even more straightforward, check out this video demonstration that walks you through the process of testing your Lambda function&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzpqgi96rs5cuxdlp3grq.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzpqgi96rs5cuxdlp3grq.gif" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For those who prefer the command line, you can use the AWS CLI along with CURL to test your Lambda function. Here’s an example CURL command:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;curl — request GET “lambda_url" — user AWS_ACCESSS_KEY:AWS_SECRET_KEY — aws-sigv4 “aws:amz:us-west-2:execute-api”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;As we wrap up our exploration of AWS Bedrock and Lambda Response Streaming, it’s evident that the synergy between these technologies can elevate your serverless architecture to new heights. By following the steps outlined in this blog, you’ve empowered your applications with enhanced efficiency and dynamic response capabilities.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Checkout my &lt;a href="https://github.com/rushi308/bedrock-genai-cdk" rel="noopener noreferrer"&gt;Github&lt;/a&gt; repository&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Happy Coding :)&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Secure Machine-to-Machine OAuth 2.0 Authentication Integration with AWS Cognito, CDK, and API Gateway</title>
      <dc:creator>Rushi Patel</dc:creator>
      <pubDate>Fri, 28 Jul 2023 15:42:52 +0000</pubDate>
      <link>https://dev.to/xushiii/secure-machine-to-machine-oauth-20-authentication-integration-with-aws-cognito-cdk-and-api-gateway-3df2</link>
      <guid>https://dev.to/xushiii/secure-machine-to-machine-oauth-20-authentication-integration-with-aws-cognito-cdk-and-api-gateway-3df2</guid>
      <description>&lt;p&gt;In today's interconnected world, machines often communicate with each other to exchange data. To protect sensitive information and maintain system integrity, it's crucial to have a secure authentication mechanism for these interactions. In this blog post, we'll explore how to achieve secure machine-to-machine authentication using AWS Cognito, AWS CDK, and API Gateway with a simple and easy-to-understand approach.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--eBiity2s--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h5k1dqy1x10mkwbugqw9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--eBiity2s--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h5k1dqy1x10mkwbugqw9.png" alt="Image description" width="800" height="398"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What is AWS Cognito?
&lt;/h2&gt;

&lt;p&gt;AWS Cognito is a fully managed authentication service by Amazon Web Services. It allows us to add user sign-up, sign-in, and access control to our applications. With Cognito, we can easily create and manage user pools, which act as directories for authentication and authorization purposes. It's a powerful tool to manage user identities and permissions effectively.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Use this Mechanism Over IAM or Other M2M Authentication Mechanisms ?
&lt;/h2&gt;

&lt;p&gt;While AWS provides several authentication mechanisms for machine-to-machine (M2M) communication, using AWS Cognito, CDK, and API Gateway offers distinct advantages that make it a preferable choice over other methods like IAM, API keys, mTLS, and EC2 instance profiles.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Fine-Grained Access Control:&lt;/strong&gt; AWS Cognito, combined with custom scopes, allows for fine-grained access control. We can define specific permissions for different types of machines, granting them access only to the necessary resources. In contrast, IAM provides broader permissions at the user or role level, which might not be as granular as required for M2M communication.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Scalability and Flexibility:&lt;/strong&gt; The integration of AWS Cognito, CDK, and API Gateway offers a scalable and flexible solution for M2M authentication. Managing client credentials within the Cognito User Pool allows us to easily add or revoke machine access, adapting to changing requirements. This dynamic control over access is not as straightforward with IAM or API keys.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;OAuth 2.0 Integration:&lt;/strong&gt; By incorporating OAuth 2.0 with AWS Cognito, we enable third-party applications to access our resources on behalf of users, enhancing the versatility of our M2M communication. This is particularly valuable when external services need secure access to specific resources while adhering to our authentication policies.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Centralized User Directory:&lt;/strong&gt; AWS Cognito acts as a centralized user directory, facilitating efficient user and machine management. This becomes particularly beneficial when multiple applications and services need access to the same user pool. IAM, API keys, and instance profiles lack the user directory capabilities of AWS Cognito, making it less suitable for managing M2M communication across various services.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reduced Risk with Client Credentials:&lt;/strong&gt; The use of unique client credentials (client ID and client secret) in the OAuth 2.0 flow reduces the risk of unauthorized access. Unlike API keys, which can be more static and shared, client credentials are tied to specific machines, and they can be easily rotated to maintain a higher level of security.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In conclusion, the combination of AWS Cognito, CDK, and API Gateway provides a powerful and secure mechanism for machine-to-machine authentication. The solution offers fine-grained access control, scalability, flexibility, and built-in token validation, making it a preferred choice over IAM, API keys, mTLS, and instance profiles. By integrating OAuth 2.0, we enhance the versatility of our M2M communication while maintaining centralized user management and ensuring robust security for resources.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting up AWS CDK for Infrastructure as Code
&lt;/h2&gt;

&lt;p&gt;To ensure a repeatable and scalable deployment process, we'll use AWS CDK as Infrastructure as Code. CDK allows you to define your cloud infrastructure using familiar programming languages like TypeScript, Python, or Java. Let's quickly go through the setup process:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Install AWS CDK CLI:&lt;/strong&gt; Follow the &lt;a href="https://docs.aws.amazon.com/cdk/v2/guide/cli.html"&gt;official documentation&lt;/a&gt; to install the AWS CDK CLI on your local machine.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Initialize a New CDK Project:&lt;/strong&gt; Create a new directory for your project and run below command to initialize a new CDK project. Here we're using typescript as a programming language.&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;cdk init app - language [csharp|fsharp|go|java|javascript|python|typescript]&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Install Necessary Dependencies:&lt;/strong&gt; Install the required AWS SDK and any other dependencies using npm or yarn.&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating an AWS Cognito User Pool with Custom Scopes
&lt;/h2&gt;

&lt;p&gt;To tailor the access permissions for our APIs, we'll create an AWS Cognito User Pool with custom scopes. Custom scopes allow us to define specific permissions, such as "read" or "write," for different types of users as per your requirement. By setting up custom scopes, we can easily manage access control for our machine-to-machine communication.&lt;/p&gt;

&lt;p&gt;Here is sample code to create UserPool and custom scopes. We've created two scopes &lt;strong&gt;"user.read"&lt;/strong&gt; and &lt;strong&gt;"user.write"&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--l5EL9Z6V--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vrtmys1zhvi95incj2yt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--l5EL9Z6V--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vrtmys1zhvi95incj2yt.png" alt="Image description" width="800" height="507"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, we'll be attached this above scopes to resource server as below&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--D13oMesg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/55djum906wjqed7y6wn1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--D13oMesg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/55djum906wjqed7y6wn1.png" alt="Image description" width="800" height="339"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementing Machine to Machine Authentication
&lt;/h2&gt;

&lt;p&gt;Machine to machine communication often involves server-to-server interactions, where authentication is done using credentials specific to the machines rather than user credentials.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Generate Client Credentials:&lt;/strong&gt; Within the Cognito User Pool, generate unique client credentials (client ID and client secret) for your machines.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Use Client Credentials:&lt;/strong&gt; Securely store these credentials on your machines and use them to obtain access tokens from Cognito for subsequent API requests. You can get access token from this access point and read &lt;a href="https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html"&gt;documentation&lt;/a&gt; here that how we can get the access token.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;All together we configured while we're creating client for the UserPool and you can customise below options as per your need. Moreover, we defined all scopes here as oAuth.&lt;/p&gt;

&lt;p&gt;Also, we configured domain for userpool, you have two option either Cognito Domain or Custom Domain. Here we set prefix text in the domain url.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: Remember the domain name should be unique all across AWS accounts.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--hDtxajx0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eev32pioeaqdmjhjky8i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--hDtxajx0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eev32pioeaqdmjhjky8i.png" alt="Image description" width="800" height="897"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementing API Gateway and Lambda
&lt;/h2&gt;

&lt;p&gt;With AWS Cognito and OAuth 2.0 set up, we'll implement API Gateway to act as the entry point for our machine-to-machine communication. We'll create a Lambda function that returns a simple response to validate the authentication process.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Qnmsgpfi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1f28xaw3wpetsplopoct.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Qnmsgpfi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1f28xaw3wpetsplopoct.png" alt="Image description" width="800" height="373"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Our Lambda is ready for rock and roll. We'll define our API Gateway (REST API)and resource(user).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--3ZxT2RwP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9mztcwl68qdpyutmqk48.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3ZxT2RwP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9mztcwl68qdpyutmqk48.png" alt="Image description" width="800" height="522"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We are going to create a new Authorizer within API Gateway, in this case CognitoUserPoolAuthorizer, with an attached UserPool that we generated before.&lt;/p&gt;

&lt;p&gt;We have now added the GET method to the user resource in order to retrieve data from our lambda. Along with that, we added the appropriate scope as needed for this method and defined the Cognito authorizer and authorization type.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Ne0Wis65--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h76bn2ndxwymkqf8znd6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Ne0Wis65--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h76bn2ndxwymkqf8znd6.png" alt="Image description" width="800" height="525"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Deploying the Solution with AWS CDK
&lt;/h2&gt;

&lt;p&gt;With all the components set up, it's time to deploy the complete solution using AWS CDK. CDK simplifies the deployment process by creating or updating the necessary resources based on the code we defined. This ensures consistency across deployments and reduces the chances of manual errors.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Deploy the Stack:&lt;/strong&gt; Run &lt;code&gt;cdk deploy&lt;/code&gt; to deploy the entire infrastructure, including AWS Cognito User Pool, API Gateway with Cognito authorizer, and any other necessary resources.&lt;/p&gt;

&lt;h2&gt;
  
  
  Testing
&lt;/h2&gt;

&lt;p&gt;Now we're ready to test whole machine-to-machine authentication using AWS Cognito and API Gateway&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;You need to get your client id and client secret from aws console. It's very sensitive&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To test our machine-to-machine authentication, we'll first get an access token using client credentials. This token represents the machine's identity and permissions.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;curl - location 'https://sample-oauth.auth.eu-west-2.amazoncognito.com/oauth2/token' \&lt;br&gt;
 - header 'Content-Type: application/x-www-form-urlencoded' \&lt;br&gt;
 - header 'Authorization: Basic NuRnbjBjNWFycWYxMXFxbTNzOGtmJnYzZ2NjEzdWtxbGNuYmNqZTdgxoiqjBuc2hhNHRxdWJwJiiXVsdmw2NYQwcDHHmNhOWnmvbIFkcg==' \&lt;br&gt;
 - data-urlencode 'grant_type=client_credentials' \&lt;br&gt;
 - data-urlencode 'scope=OauthResourceServer/user.read'&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In response, you get access token which is look like this&lt;/p&gt;

&lt;p&gt;&lt;code&gt;{&lt;br&gt;
"access_token": "access_token_value",&lt;br&gt;
"expires_in": 3600,&lt;br&gt;
"token_type": "Bearer"&lt;br&gt;
}&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;We'll then use this access token to authenticate our API Gateway requests, ensuring that only authorized machines can access our APIs.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;curl - location 'https://7scdlnkrc5.execute-api.eu-west-2.amazonaws.com/prod/user' \&lt;br&gt;
 - header 'Authorization: access_token_value'&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;If you get response as we defined in our lambda then your authorisation is granted if not then you received 401(Unauthorised) in the response.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Store the Credentials and How Often They Need to Be Rotated?
&lt;/h2&gt;

&lt;p&gt;Storing machine-to-machine (M2M) credentials securely is crucial to prevent unauthorized access and ensure the integrity of our system. The client credentials, consisting of the client ID and client secret, are used for obtaining access tokens from AWS Cognito. Here’s how we can store and manage these credentials securely:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Use Secure Storage Service:&lt;/strong&gt; Consider using AWS Secrets Manager or other secure credential management services provided by cloud platforms. These services offer encryption and access controls to safeguard sensitive information.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Credential Rotation Policy:&lt;/strong&gt; Implement a credential rotation policy to enhance security. Regularly rotate the client secret at predefined intervals. The frequency of rotation depends on your organization’s security requirements and the sensitivity of the data being accessed. A common practice is to rotate credentials every 90 days or as mandated by your security policies.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Secure Communication:&lt;/strong&gt; Ensure secure communication between machines and AWS Cognito during credential exchange. Use encrypted channels (e.g., HTTPS) when requesting access tokens to prevent eavesdropping or man-in-the-middle attacks.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Limited Access to Credentials:&lt;/strong&gt; Limit access to the credentials to authorized personnel only. Follow the principle of least privilege, granting access only to those who need it for administrative or maintenance tasks.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Remember that the security of your machine-to-machine communication heavily relies on how well you protect and manage the client credentials. Regularly assess and update your security practices to align with industry best practices and evolving security threats. By employing a robust credential management strategy, you can ensure a secure and reliable M2M authentication mechanism.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this blog post, we explored how to implement secure machine-to-machine authentication using AWS Cognito, AWS CDK, and API Gateway. By creating an AWS Cognito User Pool with custom scopes, and leveraging AWS CDK for infrastructure as code, we built a robust and scalable authentication mechanism for our machine-to-machine communication. Secure authentication is crucial for protecting sensitive data and ensuring the integrity of our systems in today's interconnected world.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;You can check my &lt;a href="https://github.com/rushicruk/cdk-cognito-m2m-oauth-authorizer"&gt;Github&lt;/a&gt; repository for more information.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Happy Coding :)&lt;br&gt;
Cheers&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Jump into Datadog With AWS Serverless CDK App</title>
      <dc:creator>Rushi Patel</dc:creator>
      <pubDate>Wed, 24 May 2023 09:41:15 +0000</pubDate>
      <link>https://dev.to/xushiii/jump-into-datadog-with-aws-serverless-cdk-app-157b</link>
      <guid>https://dev.to/xushiii/jump-into-datadog-with-aws-serverless-cdk-app-157b</guid>
      <description>&lt;p&gt;This article will help you to start using DataDog with your AWS Serverless CDK app. Now, we will see some background knowledge of DataDog.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--lBDvgt3z--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k5j88grsljmvh191xtjg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--lBDvgt3z--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k5j88grsljmvh191xtjg.png" alt="Image description" width="720" height="192"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Datadog?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Through a SaaS-based data analytics platform, Datadog offers monitoring of servers, databases, tools, and services for cloud-scale applications.&lt;/p&gt;

&lt;p&gt;You must first register with DataDog, which offers a free 14-day trial, by clicking &lt;a href="https://app.datadoghq.com/signup"&gt;this link&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You might need to configure IAM Role Policy for DataDog after successfully signing up, both manually and automatically are options.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;For Automatic (Recommend), use &lt;a href="https://medium.com/r/?url=https%3A%2F%2Fdocs.datadoghq.com%2Fgetting_started%2Fintegrations%2Faws%2F"&gt;this link&lt;/a&gt;&lt;br&gt;
For Manual, use &lt;a href="https://medium.com/r/?url=https%3A%2F%2Fdocs.datadoghq.com%2Fintegrations%2Fguide%2Faws-manual-setup%2F%3Ftab%3Droledelegation"&gt;this link&lt;/a&gt;&lt;/strong&gt;&lt;br&gt;
We’re about to start developing our AWS CDK app in typescript using typescript template. You can use the command below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir DatadogCDK

cd DatadogCDK

cdk init app — language typescript
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The NodejsService function will now be created in the file &lt;strong&gt;lib/constructs/nodejs-service-function.ts&lt;/strong&gt; and used for all of the Lamda functions in our app.&lt;br&gt;
You can use the following code and modify it according to your needs.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ZljaiRAV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5u4baxnudplliya69edn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ZljaiRAV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5u4baxnudplliya69edn.png" alt="Image description" width="720" height="630"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Note: You must install the necessary dependencies such as aws-lambda, aws-cdk, middy, esbuild and winston.&lt;/p&gt;

&lt;p&gt;We are now prepared to rock ’n’ roll in our primary stack by installing the necessary Datadog dependencies.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i datadog-cdk-constructs-v2 datadog-lambda-js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It’s time to write our first lambda, which should generate a single metric in DataDog and then just return an object. This is how your lambda should look.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--h5h4wPXW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hfpy7qab6rditxjufes8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--h5h4wPXW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hfpy7qab6rditxjufes8.png" alt="Image description" width="720" height="580"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, we’re defining our Datadog with the appropriate site and API key from your Datadog account. Then, for monitoring, we develop a single lambda function and tie it to Datadog. If you want logs of every resource in your AWS account, you can use DataDog Forwarder; more information can be found in the section below this article.&lt;/p&gt;

&lt;p&gt;Your stack appears below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rLYoahnc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5vkiimx3f88bmlhtx95g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rLYoahnc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5vkiimx3f88bmlhtx95g.png" alt="Image description" width="720" height="519"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now that we’ve had DataDog Monitoring, we’re prepared to test our lambda. You must perform the commands listed below to bootstrap and deploy your CDK application:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx cdk bootstrap

npx cdk deploy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run your lambda function when it has successfully deployed, and feel free to tweak the code if you wish to see error logs.&lt;/p&gt;

&lt;p&gt;Please wait at least &lt;strong&gt;10 minutes&lt;/strong&gt; after invoking lambda (to allow the data from lambda to Datadog to sync)&lt;/p&gt;

&lt;p&gt;I repeatedly called my function using the happy and unhappy paths, and I could clearly see the logs and fascinating information about your lambda functions.&lt;/p&gt;

&lt;p&gt;You can also see your metrics logs because our lambda includes coffee.order value. The logs panel allows you to view detailed logs. I’ve provided an example set from my DataDog Dashboard logs here.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--K1Xe8Vsy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4shupcscrlc4hivv7qng.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--K1Xe8Vsy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4shupcscrlc4hivv7qng.png" alt="Image description" width="720" height="367"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bdtXlujw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nxuezjnlnwr8iv3d01b8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bdtXlujw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nxuezjnlnwr8iv3d01b8.png" alt="Image description" width="720" height="357"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--JBQcvJ2E--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ewk0lr8tg28j071o9xno.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--JBQcvJ2E--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ewk0lr8tg28j071o9xno.png" alt="Image description" width="720" height="367"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you have the associated services then the logs are also visible for your lambda function and may be seen by exploring other DataDog features. You need to refer to the documentation for that.&lt;/p&gt;

&lt;p&gt;We will now have a look at a fascinating lambda function created by DataDog, called DataDog Forwarder.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is DataDog Forwarder?&lt;/strong&gt;&lt;br&gt;
An AWS Lambda function called the Datadog Forwarder transports logs, custom metrics, and traces from your environment to Datadog. The Forwarder is able to forward logs of AWS Services like: Cloudwatch, ELB, S3, CloudTrail, SNS, AWS lambda, Kinesis data stream, and many more.&lt;/p&gt;

&lt;p&gt;For installation, you need to follow the &lt;a href="https://docs.datadoghq.com/logs/guide/forwarder/?tab=cloudformation"&gt;documentation&lt;/a&gt; by DataDog.&lt;/p&gt;

&lt;p&gt;Here, You can find my &lt;strong&gt;[GitHub]&lt;/strong&gt;(&lt;a href="https://github.com/rushi308/cdk-datadog"&gt;https://github.com/rushi308/cdk-datadog&lt;/a&gt;) code if you want to have a look.&lt;/p&gt;

&lt;p&gt;That’s it; you now have a foundational understanding of how DataDog fits into your Serverless architecture.&lt;/p&gt;

&lt;p&gt;Happy Coding!! Cheers&lt;/p&gt;

</description>
      <category>aws</category>
      <category>serverless</category>
      <category>datadog</category>
      <category>awscdk</category>
    </item>
  </channel>
</rss>
