API Security - Communication and Authentication

Fundamentals of Application Programming Interfaces

  • Definition of API:

    • An Application Programming Interface (API) is an interface that allows external programs and third-party systems to programmatically access and execute the capabilities, business logic, or data of an application.

    • APIs serve as the foundational communication layer connecting distributed systems, mobile devices, external partner integrations, and microservices.

  • Web API Growth Trajectory:

    • According to industry tracking by ProgrammableWeb, the total count of publicly registered Web APIs grew from near 00 in January 2006 to over 22,00022{,}000 by January 2018.

    • This rapid rise underscores the necessity of standardizing API security patterns across communication and authentication layers.

Growth in Web APIs Since 2005
  • Technical Specification Profile: Twitter Direct Messages API v1.1:

    • API Endpoint: https://api.twitter.com/1.1/direct_messages/

    • API Portal / Documentation: https://developer.twitter.com/en/docs/direct-messages/api-features

    • Primary Category: Social

    • Secondary Categories: Customer Service, Marketing, Messaging, Tweets

    • API Provider: Twitter

    • SSL Support: Yes (Mandatory)

    • Twitter Developer URL: https://twitter.com/twitterdev

    • Authentication Model: OAuth 2, Token

    • Version: 1.11.1

    • Version Status: Recommended (active, supported)

    • Terms Of Service URL: https://developer.twitter.com/en/developer-terms

    • Non-Proprietary Design / Description: Yes

    • Type: Web/Internet

    • Scope: Single purpose API

  • API Interaction via Direct HTTP Request:

    • Creating a direct message event requires signed headers and a structured JSON payload.

    • cURL invocation using OAuth 1.0 Authorization headers: bash curl --request POST \ --url https://api.twitter.com/1.1/direct_messages/events/new.json \ --header 'authorization: OAuth oauth_consumer_key="YOUR_CONSUMER_KEY", oauth_nonce="AUTO_GENERATED_NONCE", oauth_signature="AUTO_GENERATED_SIGNATURE", oauth_signature_method="HMAC-SHA1", oauth_timestamp="AUTO_GENERATED_TIMESTAMP", oauth_token="USERS_ACCESS_TOKEN", oauth_version="1.0"' \ --header 'content-type: application/json' \ --data '{"event": {"type": "message_create", "message_create": {"target": {"recipient_id": "RECIPIENT_USER_ID"}, "message_data": {"text": "Hello World!"}}}}'     

  • Command line execution using twurl: bash twurl -A 'Content-type: application/json' -X POST /1.1/direct_messages/events/new.json -d '{"event": {"type": "message_create", "message_create": {"target": {"recipient_id": "RECIPIENT_USER_ID"}, "message_data": {"text": "Hello World!"}}}}'     

  • Event payload format: json { "event": { "type": "message_create", "message_create": { "target": { "recipient_id": "RECIPIENT_USER_ID" }, "message_data": { "text": "Hello World!" } } } }     

Implementation and Interception Risks in Microservice APIs

  • Microservice Architecture and Controller Design:

    • Microservices expose specific domain functionalities via specialized controllers.

    • Implementation example from FleetManagementLab – UsageController.java (package edu.microserviceslab.usagemicroservice.controller): ```java @RestController @RequestMapping("/usage") public class UsageController { private UsageService usageService;

      public UsageController(UsageService usageService) { this.usageService = usageService; }

      @ResponseBody @RequestMapping("/list") public List listAllUsageStatistics() { return usageService.getAllUsageStatistics(); }

      @ResponseBody @RequestMapping("/vehicle/{vehicleId}") public List listAllUsageStatisticsForVehicle(@PathVariable("vehicleId") Long vehicleId) { return usageService.getUsageStatisticsPerVehicle(vehicleId); }

      @ResponseBody @RequestMapping(path = "/add", method = RequestMethod.POST) public List addUsageStatistic(@RequestBody UsageStatisticRequest usageStatisticRequest) { List usageStatistics = new LinkedList<>(); for (PidRequest pidRequest : usageStatisticRequest.getPids()) { UsageStatistic usageStatistic = new UsageStatistic(); usageStatistic.setVehicleId(usageStatisticRequest.getVehicleId()); usageStatistic.setPid(pidRequest.getPid()); usageStatistic.setData(pidRequest.getData()); // persistence logic } return usageStatistics; } }     ```

  • Exposure of Sensitive Data over Unencrypted HTTP:

    • Consider a Spring Boot controller handling retail order lookup: java @RestController @RequestMapping(value = "/order") public class OrderProcessing { @RequestMapping(value = "/{id}", method = RequestMethod.GET) public String checkOrderStatus(@PathVariable("id") String orderId) { return ResponseEntity.ok("{'status' : 'shipped'}"); } } &nbsp;&nbsp;&nbsp;&nbsp;

  • Calling the API endpoint over cleartext HTTP: bash curl http://localhost:8080/order/11 &nbsp;&nbsp;&nbsp;&nbsp;

  • Returned JSON payload exposed in transit: json { "customer_id": "101021", "order_id": "11", "payment_method": { "card_type": "VISA", "expiration": "01/22", "name": "John Doe", "billing_address": "201, 1st Street, San Jose, CA" }, "items": [ {"code": "101", "qty": 1}, {"code": "103", "qty": 5} ], "shipping_address": "201, 1st Street, San Jose, CA" } &nbsp;&nbsp;&nbsp;&nbsp;

  • Cleartext HTTP transmission leaves personally identifiable information (PII), credit card expiration dates, billing addresses, and physical locations exposed to packet sniffing, man-in-the-middle (MitM) eavesdropping, and tampering.

Transport Layer Security (TLS/SSL) for APIs

  • The SSL/TLS Handshake Protocol:

    • Transport Layer Security (TLS), historically termed Secure Sockets Layer (SSL), secures communication between a client application and an API server through cryptographic authentication and symmetric session encryption.

SSL Handshake Protocol Messages
  • Step-by-step SSL message exchange:

    1. Client hello: Client transmits supported cipher suites, TLS version, and a client random string.

    2. Server hello: Server selects the cipher suite, provides server random string, and confirms TLS version.

    3. Certificate (optional): Server provides its X.509 digital certificate chain to prove identity.

    4. Certificate request (optional): Server requests client identification certificate (used for mutual TLS).

    5. Server key exchange (optional): Transmits key agreement parameters (e.g., Diffie-Hellman ephemeral parameters).

    6. Server hello done: Signals the end of the server greeting phase.

    7. Certificate (optional): Client transmits its digital certificate if previously requested by the server.

    8. Client key exchange: Client sends the premaster secret (encrypted with the server's public key) or key agreement data.

    9. Certificate verify (optional): Client provides a cryptographically signed hash proving private key ownership.

    10. Change cipher spec (Client): Client indicates subsequent messages will be symmetrically encrypted.

    11. Finished (Client): Encrypted message confirming successful handshake from the client side.

    12. Change cipher spec (Server): Server indicates subsequent messages will be symmetrically encrypted.

    13. Finished (Server): Encrypted message confirming successful handshake from the server side.

    14. Encrypted data: Full bidirectional transmission of application data encrypted using negotiated session keys.

    15. Close messages: Cryptographic notification closing the secure session cleanly.

    • Configuring Server-Side SSL in Spring Boot:

  • Step 1: Generate a private key and self-signed certificate in a Java KeyStore using JDK keytool: bash keytool -genkey -alias spring -keyalg RSA -keysize 4096 -validity 3650 -dname "CN=foo,OU=bar,O=zee,L=sjc,S=ca,C=us" -keypass springboot -keystore keystore.jks -storeType jks -storepass springboot &nbsp;&nbsp;&nbsp;&nbsp;

  • Key algorithm: RSA

  • Key size: 4096 bits4096\,\text{bits}

  • Validity period: 3650 days3650\,\text{days} (10 years10\,\text{years})

  • Distinguished Name (DN): CN=foo, OU=bar, O=zee, L=sjc, S=ca, C=us

  • Keystore file: keystore.jks with type jks

  • Passwords: springboot

    • Step 2: Configure Spring Boot's application.properties to bind the KeyStore:

    server.ssl.key-store: keystore.jks
    server.ssl.key-store-password: springboot
    server.ssl.keyAlias: spring
    &nbsp;&nbsp;&nbsp;&nbsp;```
    - Step 3: Invoke the secure API over HTTPS:
    

    bash curl -k https://localhost:8080/order/11     ```

    • The -k flag instructs cURL to bypass local CA certificate verification for self-signed certificates.

    • Validating Server Certificates via Certificate Authority (CA):

  • Step 1: Export the public certificate from the server keystore into an RFC-compliant (PEM) certificate file: bash keytool -export -file ca.crt -alias spring -rfc -keystore keystore.jks -storePass springboot &nbsp;&nbsp;&nbsp;&nbsp;

    • Step 2: Attempt cURL execution verifying against the exported ca.crt: bash curl --cacert ca.crt https://localhost:8080/order/11 &nbsp;&nbsp;&nbsp;&nbsp;

  • Error encountered:     curl: (51) SSL: certificate subject name 'foo' does not match target host name 'localhost'

  • Root Cause: The Common Name (CN) specified during certificate creation was foo, which does not match the requested hostname localhost.

    • Step 3: Resolving Subject Name Mismatch via DNS Resolution Mapping: bash curl --cacert ca.crt https://foo:8080/order/11 --resolve foo:8080:127.0.0.1 &nbsp;&nbsp;&nbsp;&nbsp;

    • The --resolve flag forces cURL to route requests for host foo on port 80808080 directly to IP address 127.0.0.1, matching the subject name while preserving strict SSL certificate verification.

Mutual Transport Layer Security (mTLS)

  • Concept and Purpose of Mutual SSL:

    • While standard SSL only authenticates the server to the client, Mutual SSL (mTLS) enforces two-way cryptographic verification where the client must also present a valid, server-trusted X.509 digital certificate.

  • Enforcing Client Authentication in Spring Boot:

    • Update application.properties to mandate client certificates: properties server.ssl.key-store: keystore.jks server.ssl.key-store-password: springboot server.ssl.keyAlias: spring server.ssl.client-auth: need &nbsp;&nbsp;&nbsp;&nbsp;

  • Setting server.ssl.client-auth to need instructs the embedded web server (e.g., Tomcat) to abort any TLS handshake that lacks a valid client certificate.

  • Execution attempt without client certificate: bash curl -k https://localhost:8080/order/11 &nbsp;&nbsp;&nbsp;&nbsp;

    • Error output:       curl: (35) error:1401E412:SSL routines:CONNECT_CR_FINISHED:sslv3 alert bad certificate

  • Implementing Client Authentication:

    • Generate client private key and certificate using OpenSSL:

    • Generate private key privkey.pem.

    • Generate client certificate client.crt.

    • Import the client's public certificate client.crt into the server application's truststore.

    • Invoke the mutual TLS-protected endpoint with client key and certificate: bash curl -k --key privkey.pem --cert client.crt https://localhost:8080/order/11 &nbsp;&nbsp;&nbsp;&nbsp;

API Authorization and Access Delegation Principles

  • Core Resource Reference:

    • Foundational architectural patterns and OAuth 2.0 implementations derive from Advanced API Security: OAuth 2.0 and Beyond (Second Edition) by Prabath Siriwardena (Apress).

  • The Authorization Problem in Modern Web APIs:

    • Securing communications via TLS/SSL ensures data privacy in transit, but does not solve authorization: determining whether a specific client or third-party entity has permission to act on behalf of a user.

    • Example scenario: Allowing a third-party social media aggregator to retweet or lookup retweeters on Twitter:     https://api.twitter.com/2/tweets/1354143047324299264/retweeted_by?user.fields=created_at&expansions=pinned_tweet_id&tweet.fields=create...

  • Strategies for Third-Party API Access:

    • Direct Credential Sharing (Anti-pattern):

    • The user provides their raw username and password to the third-party application.

    • Vulnerabilities: Third-party applications store cleartext passwords, user permissions cannot be scoped to specific actions, access cannot be revoked without changing the master password, and a breach of the third party compromises the user's primary identity.

    • Time-Bounded Tokens (OAuth 2.0 Pattern):

    • The user authenticates directly with the identity provider (authorization server).

    • The third party receives a short-lived, cryptographically signed, time-bounded token constrained to specific permissions (scopes).

  • Access Delegation Mechanics:

Access Delegation Architecture
  • Architectural flow illustrated through third-party Facebook integration:

    1. Third-party web application initiates request, redirecting the user to Facebook with the message: "E.g., we want you to like our product".

    2. Facebook prompts for user authentication and explicit consent by redirecting the user's browser to the login/consent page.

    3. User authenticates and grants access to the web application specifically to read status messages.

    4. Third-party web application receives an access token authorized strictly to read status messages on behalf of the user.

    5. Third-party application accesses Facebook API using the token to read status messages (Succeeds).

    6. If the application attempts to access the Facebook API to read the user's friend list with that same token, the request fails due to lack of authorization scope.

OAuth 2.0 Architecture and Roles

  • Core Defined Roles:

    • Resource Owner: The entity capable of granting access to a protected resource (e.g., an end user / Facebook user).

    • Resource Server: The host server holding the protected resource, capable of accepting and responding to protected resource requests using access tokens (e.g., Facebook API).

    • Client: The application requesting access to protected resources on behalf of the resource owner and with its authorization (e.g., third-party web application).

    • Authorization Server: The identity provider that authenticates the resource owner, obtains consent, and issues access tokens to registered clients.

  • Client Registration Prerequisite:

    • Any client application accessing an OAuth 2.0 system must be registered with the authorization server.

    • The authorization server provisions credentials to the client:

    • client_id: A public identifier unique to the client application.

    • client_secret: A confidential secret key known only to the application and authorization server.

OAuth 2.0 Grant Types and Workflows

  • Grant Type Definition:

    • A grant type defines the precise protocol sequence and exchange mechanism by which a client acquires an authorization grant and subsequent access token.

  • Grant Type 1: Client Credentials Grant:

    • Intended Use: Machine-to-machine (M2M) communication, autonomous daemons, or background services where the client application owns the resource or acts solely on its own behalf.

Client Credentials Grant Workflow
  • Step-by-Step Flow:

    1. Client sends client_id and client_secret directly to the authorization server via HTTP Basic authentication.

    2. Authorization server validates client_id against client_secret and issues an access token.

  • Client Request: bash curl -v -k -X POST --basic -u 0rhQErXIX49svVYoXJGt0DWBuFca:eYOFkL756W8usQaVNgCNkz9C2D0a \ -H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" \ -d "grant_type=client_credentials" \ https://authz.example.com/oauth2/token &nbsp;&nbsp;&nbsp;&nbsp;

  • Server Response: json { "token_type": "bearer", "expires_in": 3600, "access_token": "4c9a9ae7463ff9bb93ae7f169bd6a" } &nbsp;&nbsp;&nbsp;&nbsp;

    • Token lifetime: 3600 seconds3600\,\text{seconds} (1 hour1\,\text{hour}).

  • Grant Type 2: Resource Owner Password Credentials Grant:

    • Intended Use: Highly trusted legacy applications where the user enters credentials directly into the client interface.

Resource Owner Password Credentials Grant Flow
  • Step-by-Step Flow:

    1. User provides raw username and password to the client application.

    2. Client application packages user credentials with its own embedded client_id and client_secret into a token request sent to the authorization server.

    3. Authorization server validates both user credentials and client credentials, returning an access token and a refresh token.

  • Client Request: bash curl -v -k -X POST --basic -u 0rhQErXIX49svVYoXJGt0DWBuFca:eYOFkL756W8usQaVNgCNkz9C2D0a \ -H "Content-Type:application/x-www-form-urlencoded;charset=UTF-8" \ -d "grant_type=password&username=admin&password=admin" \ https://authz.example.com/oauth2/token &nbsp;&nbsp;&nbsp;&nbsp;

  • Server Response: json { "token_type": "bearer", "expires_in": 685, "refresh_token": "22b157546b26c2d6c0165c4ef6b3f736", "access_token": "cac93e1d29e45bf6d84073dbfb460" } &nbsp;&nbsp;&nbsp;&nbsp;

    • Token lifetime: 685 seconds685\,\text{seconds}.

  • Grant Type 3: Implicit Grant:

    • Intended Use: Historically designed for browser-based Single Page Applications (SPAs) without a backend to store secrets.

Implicit Grant Flow
  • Step-by-Step Flow:

    1. Client initiates authorization request, redirecting user agent (browser) to the authorization server.

    2. Authorization server opens user agent interface to prompt for credentials.

    3. Resource owner submits credentials for authentication.

    4. Browser posts user credentials to the authorization server.

    5. Authorization server redirects back to the client callback, transmitting the access token directly within the URI fragment hash.

  • Security Caveat: There is no verification of client identity (no client_secret check), exposing access tokens directly to browser history and script injection.

  • Browser Authorization Request: http https://authz.example.com/oauth2/authorize?response_type=token&client_id=0rhQErXIX49svVYoXJGt0DWBuFca&redirect_uri=https%3A%2F%2Fmycallback &nbsp;&nbsp;&nbsp;&nbsp;

  • Authorization Server URI Fragment Redirect: http https://callback.example.com/#access_token=cac93e1d29e45bf6d84073dbfb460&expires_in=3600 &nbsp;&nbsp;&nbsp;&nbsp;

  • Grant Type 4: Authorization Code Grant:

    • Intended Use: Standard, secure delegated access flow for web applications capable of protecting a client_secret on a server backend.

Authorization Code Grant Flow
  • Step-by-Step Flow:

    1. Client initiates authorization grant request by redirecting user to authorization server via browser.

    2. Authorization server prompts user agent for credentials.

    3. Resource owner submits credentials for authentication.

    4. Browser posts user credentials to authorization server.

    5. Authorization server redirects user back to client application's registered redirect URI with a short-lived authorization code (code).

    6. Client application exchanges the authorization code alongside its client_id and client_secret directly with the authorization server via a back-channel request.

    7. Authorization server validates code and client credentials, issuing an access token and refresh token.

  • Step 1: Front-Channel User Authorization Request: http https://authz.example.com/oauth2/authorize?response_type=code&client_id=0rhQErXIX49svVYoXJGt0DWBuFca&redirect_uri=https%3A%2F%2Fmycallback &nbsp;&nbsp;&nbsp;&nbsp;

  • Step 2: Front-Channel Code Delivery Redirect: http https://callback.example.com/?code=9142d4cad58c66d0a5edfad8952192 &nbsp;&nbsp;&nbsp;&nbsp;

  • Step 3: Back-Channel Token Exchange Request: bash curl -v -k -X POST --basic -u 0rhQErXIX49svVYoXJGt0DWBuFca:eYOFkL756W8usQaVNgCNkz9C2D0a \ -H "Content-Type:application/x-www-form-urlencoded;charset=UTF-8" \ -d "grant_type=authorization_code&code=9142d4cad58c66d0a5edfad8952192&redirect_uri=https://mycallback" \ https://authz.example.com/oauth2/token &nbsp;&nbsp;&nbsp;&nbsp;

  • Step 4: Token Response: json { "token_type": "bearer", "expires_in": 3600, "refresh_token": "22b157546b26c2d6c0165c4ef6b3f736", "access_token": "cac93e1d29e45bf6d84073dbfb460" } &nbsp;&nbsp;&nbsp;&nbsp;

  • End-to-End Implementation: Sign in with Twitter:

Twitter OAuth 2.0 Authorization Code Flow
  • Documentation Reference: https://developer.twitter.com/en/docs/authentication/oauth-2-0/authorization-code

  • Complete lifecycle:

    1. User clicks Sign in with Twitter.

    2. Client application prepares authorization URL and redirects user.

    3. Twitter presents authorization dialogue to user.

    4. User selects Authorize or Decline.

    5. If user declines: Twitter redirects to callback; app handles rejection.

    6. If user authorizes: Twitter redirects to app callback with authorization code.

    7. Client backend exchanges authorization code for an access token.

    8. Authorization server returns access token; user is authorized.

    • Programmatic Python OAuth Session Implementation:

  • Reference implementation from Twitter API v2 code sample (get_tweets_with_user_context.py): ```python

    1. Obtain user PIN consent via authorization URL

    print("Please go here and authorize: %s" % authorization_url) verifier = input("Paste the PIN here: ")

    2. Exchange credentials and PIN for access tokens

    access_token_url = "https://api.twitter.com/oauth/access_token" oauth = OAuth1Session( consumer_key, client_secret=consumer_secret, resource_owner_key=resource_owner_key, resource_owner_secret=resource_owner_secret, verifier=verifier, ) oauth_tokens = oauth.fetch_access_token(access_token_url) access_token = oauth_tokens["oauth_token"] access_token_secret = oauth_tokens["oauth_token_secret"]

    3. Execute authorized request against protected endpoint

    oauth = OAuth1Session( consumer_key, client_secret=consumer_secret, resource_owner_key=access_token, resource_owner_secret=access_token_secret, ) params = {"ids": "1278747501642657792"} response = oauth.get("https://api.twitter.com/2/tweets", params=params)     ```

Access Token Transmission Methods and Modern Best Practices

  • Transmission Mechanisms to Access APIs:

    • Method 1: HTTP Authorization Header (Standard and Recommended): http GET /resource HTTP/1.1 Host: rs.example.com Authorization: Bearer JGjhgyuyibGGjgjkjdlsjkjdsd &nbsp;&nbsp;&nbsp;&nbsp;

    • Most secure method; prevents leakage in URLs, browser histories, and server logs.

  • Method 2: URI Query Parameter: http GET /resource?access_token=JGjhgyuyibGGjgjkjdlsjkjdsd HTTP/1.1 Host: rs.example.com &nbsp;&nbsp;&nbsp;&nbsp;

    • Security Vulnerability: Tokens placed in query strings are captured in server access logs, proxy caching logs, and Referer headers.

  • Method 3: Form-Encoded Body Parameter: ```http POST /resource HTTP/1.1 Host: server.example.com Content-Type: application/x-www-form-urlencoded

    access_token=JGjhgyuyibGGjgjkjdlsjkjdsd     ```

    • Permissible for POST requests, but less universal than header transmission.

  • Grant Type Decision Matrix:

    • Obsolete Grant Types:

    • Implicit Grant is obsolete because tokens are exposed via URL hashes and client identity is unverified.

    • Resource Owner Password Credentials Grant is obsolete because it exposes raw user credentials to client applications.

    • Active Standards:

    • If the client application owns the resources or operates autonomously (M2M): Use Client Credentials Grant.

    • If the user delegates access permissions to an application: Use Authorization Code Grant (enhanced with PKCE for native/SPA clients).

  • Summary of API Security Architecture:

    • Comprehensive API protection requires resolving two distinct layers:

    1. Communication Layer (Transport Security): Use SSL/TLS to encrypt network transit; implement Mutual SSL (mTLS) when clients must be authenticated at the transport level.

    2. Authentication and Authorization Layer (Access Control): Use OAuth 2.0 to issue time-bounded tokens; employ Client Credentials for server-to-server APIs and Authorization Code for user delegation.