REST API Secure Coding Practices
Always use TLS/ HTTPS encryption
Enforce minimum TLS versions and disable weak cipher suites
Potentially use client side encryption on sensitive data for more guarantees
Implement Authentication and Authorization model
Authentication, Authorization and Access Control must be implemented at each endpoint
Least privilege principle: Users and systems should have the minimum access necessary to perform their duties.
Explicit Approval required: Once a user is authenticated, ensuring they can’t access resources without explicit authorization prevents risks of unauthorized data exposure.
Systems should deny access to all resources by default, only allowing access if a user/role is supposed to be present. Ensure that new components have their access policies defined before launching them.
Authorization should be checked every time resources are accessed, to prevent outdated/cached permissions being used. Token based systems like OAuth2 or JWT can ensure this. More info on JWT security.
Sanitize Input Parameters
In general, user input should not be trusted and must be checked for format correctness and sanitized to prevent injection attacks.
Validate input length/range/format/type, reject unsupported input
Regexes may be useful for confirming data conforms to format requirements
Utilize sanitation libraries/functions and query parameterization functions in whichever language is used
Ensure external libraries are secure or that introducing a new dependency is necessary
Use secure parsers for XML and other parsing needs
Log validation failures to detect users who may be attempting to pass invalid data.
Don’t include sensitive information in URLs
HTTP POST/PUT requests should have sensitive data in request body or headers
GET requests should have sensitive data in an HTTP header
If tokens/IDs need to be sent in the URL, try not to log these
Narrowly define allowed RESTful API requests and responses
APIs should return consistent, generic error messages that don’t expose internal details - no stack traces
Use proper HTTP response codes to ensure users know exactly what they need to know about successes or failures
Log where relevant
Ensure sequenced API calls occur in the proper sequences
Don’t use front-end logic to ensure sequencing
Reject out of order responses
Return only what a request asks for
Cross-Origin Resource Sharing (CORS)
Disable CORS if external sites shouldn’t have access to this
Be as specific as possible as to who’s allowed to use these
Useful Resources
https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html
Other Sources
https://www.akamai.com/blog/security/rest-api-security-best-practices