Add Authentication to Portman API tests

ADD SECURITY TO API GATEWAY

To add API Key authentication to the API we will be adding the Auth property in the API resource in the SAM template as shown below:

ProductsAPI: 
Type: AWS::Serverless::Api
Properties:
StageName: Lambdaless
Auth:
ApiKeyRequired: true
UsagePlan:
CreateUsagePlan: PER_API
UsagePlanName: ProductsAPIUsagePlan
DefinitionBody:
'Fn::Transform':
Name: AWS::Include
Parameters:
Location: ./products-openapi.yaml
ApiKeyId:     
Description: API Key ApiKeyId
Value: !Ref ProductsAPIApiKey

GET THE API KEY

There are two ways you can get the API Key that was generated:

  • Go to the console and retrieve it from the API Gateway service
  • With the CLI. Below I will be explaining how to do it from the CLI.

ADD SECURITY DEFINITIONS IN THE OPENAPI

If you try to run Portman right now you will get 403 Forbidden responses because Portman is not providing an API key to the request. Portman uses your OpenAPI definition to generate and run the tests, if we do not define the securitySchemes it will not know to apply them. So first we need to setup the securitySchemes supported by our API which in our case is only API Key, to do this we will add the following YAML under the components section of our OpenAPI spec.

securitySchemes:
ApiKeyAuth:
type: apiKey
in: header
name: X-API-KEY
security:   
- ApiKeyAuth: []

CONFIGURE PORTMAN TO USE AN API KEY

Portman allows you to configure securityOverwrites in the globals section of your Pormtan config file. We will be updating ours to include an overwrite for the apiKey.

{   
"securityOverwrites": {
"apiKey": {
"value": "INSERT THE API KEY HERE"
}
}
}

RECAP

In this post we successfully tested a secure API using Portman by

  • Adding security to the API
  • Updating the OpenAPI spec to define the type of authentication to be used
  • Configured Portman to successfully include an API key in the header of every request to be able to automate our API testing for secure APIs

--

--

Passionate software engineer focused on cloud development.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Andres Moreno

Andres Moreno

Passionate software engineer focused on cloud development.