Validate security headers in API response
Preconditions (2)
✅ Expected Result: All listed security headers are present in the response with the exact expected values.
pm.test('Validate Content-Security-Policy header', () => { const csp = pm.response.headers.get('Content-Security-Policy'); pm.expect(csp).to.eql("default-src 'self'"); }); pm.test('Validate X-Content-Type-Options header', () => { const xcto = pm.response.headers.get('X-Content-Type-Options'); pm.expect(xcto).to.eql('nosniff'); }); pm.test('Validate Strict-Transport-Security header', () => { const sts = pm.response.headers.get('Strict-Transport-Security'); pm.expect(sts).to.eql('max-age=31536000; includeSubDomains'); }); pm.test('Validate X-Frame-Options header', () => { const xfo = pm.response.headers.get('X-Frame-Options'); pm.expect(xfo).to.eql('DENY'); }); pm.test('Validate Referrer-Policy header', () => { const rp = pm.response.headers.get('Referrer-Policy'); pm.expect(rp).to.eql('no-referrer'); });
This Postman test script checks each required security header individually.
Each pm.test block names the header it validates for clarity.
We use pm.response.headers.get() to get the header value by name.
The pm.expect(...).to.eql(...) assertion checks that the header value exactly matches the expected string.
This approach ensures clear, maintainable tests that will fail if any header is missing or has an incorrect value.
Now add data-driven testing with 3 different API endpoints to validate security headers on each.
X-Frame-Options header controls if a page can be framed.Content-Security-Policy header exists in the response?pm.response.headers.get() returns the header value or null if missing.X-Content-Type-Options is missing?
pm.test('X-Content-Type-Options header is set', () => {
pm.response.to.have.header('X-Content-Type-Options');
});pm.response.to.have.header() asserts the header must exist.Strict-Transport-Security header includes max-age=31536000:
pm.test('HSTS max-age check', () => {
pm.expect(pm.response.headers.get('Strict-Transport-Security')).to.include('max-age=31536000');
});Content-Security-Policy header disallows inline scripts by including script-src 'self'. Which test script correctly validates this?script-src 'self'.to.include checks if the string contains the directive, allowing other parts.Pass the test and this pattern moves unknown