Most applications today expose an API to facilitate seamless interaction with their features and data. However, ensuring the security of your API is essential for various reasons:
- Restrict Access to Authorized Users - Only authenticated users should have access to sensitive functions and data within your API, ensuring that internal information is protected from unauthorized exposure.
- Control and Monitor Data Access - By enforcing authentication, you can prevent unauthorized access to data, allowing only verified users to make requests and interact with resources, which significantly reduces potential data leaks.
- Protect Against Common Security Threats - Securing your API helps safeguard it from attacks like unauthorized data scraping, injection attacks, and brute force attacks, adding a critical layer of defense against malicious actors.
- Ensure Data Integrity and Privacy - When users access your API, you want to ensure that their data remains secure and uncompromised. Proper security protocols help guarantee that data remains intact and private during transit.
- Enable Scalability with Controlled Access - With secure API endpoints, you can scale your application more confidently, knowing that only authorized and authenticated users can access each part, reducing the risk of system overload due to malicious requests.
In this post, I’ll walk you through securing your API using JWT Authorizers and Amazon Cognito. But first, let’s clarify what a JWT is and why it’s crucial in securing APIs.
What is a JWT Token?
- JSON Web Token - A standard format for securely transmitting information between parties as a JSON object.
- Acts as a Secure Identifier for Authenticated Users - Think of it as a secure, encoded token that verifies the identity of authenticated users.
- Contains a Verifiable Digital Signature - Each token has a digital signature that our API can validate, ensuring the token’s authenticity and integrity.
- Provided by Authentication Services (e.g., AWS Cognito) - Services like AWS Cognito validate the user’s credentials at login and issue a token, which the user includes in every API request for continued access.
How to Set Up Authorization in AWS
Step 1: Create a Lambda Function
- Start by creating a Lambda function in AWS. This function will handle your API requests.
Step 2: Set Up an API Gateway
- Navigate to API Gateway in the AWS Console.
- Create a new REST API.
Step 3: Connect Your Lambda to a GET Method
- Select "Create Method" under your API.
- Modify settings as highlighted below to connect your Lambda function to a GET method.
Step 4: Deploy Your API
- Click on "Deploy API."
- Create a new Stage if you don't already have one.
Step 5: Test Your API Endpoint
- Copy the Invoke URL from your API.
- Paste it into a browser to test the response from your Lambda function.
Adding Security to Your API
Step 6: Create a User Pool in Amazon Cognito
- Go to Cognito in the AWS Console
- Click Create user pool
- For the Cognito user pool sign-in options, select Email
- Click Next
- For simplicity of this demo select No MFA
- Click Next twice
- For the Configure message delivery select Send email with Cognito
- Click Next and give your user pool a name and also an app client name
- Click Next and then Create user pool
Step 7: Create a test user
- Click on your newly created user pool
- Select Users and Create user
- Create your user
Step 8: Set Up the App Integration
- Click on your user pool that you just created
- Click on App integration
- Click on your app client that you created earlier
- Click on Hosted UI
- Add the following settings:
- Callback URL: https://localhost
- Sign-out URL: https://localhost
- Identity provider: Cognito user pool
- OAuth 2.0 grant types: Implicit grant
- OpenID Connect scopes: Select all options
- Click Save changes
Step 9: Create a Domain for Your User Pool
- Go back to your main user pool page
- Click on Domain --> Actions --> Create Cognito domain
- Add the desired domain and check if it's available
- Create it
Testing and Parsing the JWT
Step 10: Test your login with the Hosted UI
- Go back to your main user pool page
- Scroll down to the bottom to the App client list
- Click on your app client
- Scroll down to Hosted UI
- To the right click on View Hosted UI
- Login with the credentials that you should have got in the email that you provided earlier
- If the login is successful you should come to your callback URL which is https://localhost
Step 11: Parse our JWT
Let's parse our JWT now and explore it.
- Go back to your main user pool page
- Scroll down to the bottom to the App client list
- Click on your app client
- Scroll down to Hosted UI
- Right click on View Hosted UI and copy the URL
- Open Postman (or a similar tool)
- Create a new request
- Click on Authorization
- Give the token a name
- Grant type: Implicit
11: Auth URL: paste the URL that you copied from the hosted zone
12: Click on the button Get New Access Token
13: Login with your user
14: Copy the
id_token
Step 12: Exploring the Contents of Your JWT
- Go to jwt.io
- Paste your
id_token
- On the right side you'll see your decoded payload data
Securing Your API with the JWT Authorizer
Step 13: Create an authorizer
- Go to your API that you created
- For your GET method you'll see that you don't have any authorization added
- To add this click on Authorizers on the left pane
- Click on Create authorizers
- Add the settings you see below
- Create authorizer
- You can now click on your newly created authorizer and test it in the console directly
Step 14: Now let's update our method with our new authorizer
- Go back to your GET method in your API
- On the Method request settings select Edit
- On the Authorization select your newly created authorizer
- Click Save and the redeploy your API
Step 15: Let's test our new API endpoint with our authorizer
- Go back to Postman to your request and use your GET method and click Send
- You should now get:
{
"message": "Unauthorized"
}
But let's generate a token and then add a new Header:
Key: Authorization
Value: Your id_token
Click send and you should now see:
"Hello from Lambda!"
Conclusion
Congratulations! You’ve successfully secured your API using JWT authorizers and Amazon Cognito. This setup provides robust authentication, ensuring only authorized users access your resources. With stateless JWTs, your API scales effortlessly without session management overhead. Plus, strong API security builds user trust and helps meet compliance standards.
With this foundation, your API is more secure, scalable, and ready to grow alongside your application’s needs.
Top comments (0)