Designing Secure API Authentication with Token and Signature in Java
This article explains how to secure app open‑API endpoints by using HTTPS, token‑based authentication, timestamp validation, and a URL‑signature algorithm implemented in Java, including detailed steps, interception rules, and sample code for generating and verifying signatures.
In the design of open‑API interfaces for mobile apps, security is critical because many endpoints handle personal and sensitive data; therefore, authentication mechanisms such as username/password should be minimized in plaintext and typically stored in server‑side sessions and cookies.
For open APIs, the backend must verify a user's login status after authentication, similar to token verification used by platforms like Taobao and WeChat. The solution described follows the same principle: after a successful login, the server issues a unique token that the client includes in subsequent requests.
HTTPS Requirement All sensitive API calls must be made over HTTPS, which adds an SSL layer to encrypt traffic. HTTPS requires a CA‑issued certificate, usually a paid service.
Signature Design After login, the client receives a token and must include the following parameters in each request: timestamp and token. All request parameters (including these two) are sorted alphabetically, concatenated, optionally salted, and then hashed with MD5 (converted to uppercase) to produce a sign value. The final request URL contains timestamp, token, and sign.
Example request flow:
1. Client sends login credentials (username, password) to the server. 2. Server validates credentials and returns a unique token (often a UUID). The token‑uid mapping is stored in Redis for quick lookup.
3. For each protected API call, the client adds timestamp, token, and generates sign as described.
Interception Rules on the Server
Check that timestamp, token, and sign are present; otherwise return an error.
Verify that the request timestamp is within an acceptable window (e.g., 30 minutes) to prevent replay attacks.
Validate the token by looking up the uid in Redis; if missing, the token is expired.
Re‑create the signature on the server using the same algorithm and compare it with the received sign. If they match, the request is allowed.
Only authentication‑related URLs (e.g., login) are exempt from interception; all other URLs must pass the checks.
Token‑Uid Relationship Maintenance When a user logs out, the corresponding token‑uid entry must be removed from Redis.
Signature Implementation (Java)
String sign = request.getParameter("sign");
Enumeration<?> pNames = request.getParameterNames();
Map<String, Object> params = new HashMap<String, Object>();
while (pNames.hasMoreElements()) {
String pName = (String) pNames.nextElement();
if ("sign".equals(pName)) continue;
Object pValue = request.getParameter(pName);
params.put(pName, pValue);
}Generating the signature:
public static String createSign(Map<String, String> params, boolean encode) throws UnsupportedEncodingException {
Set<String> keysSet = params.keySet();
Object[] keys = keysSet.toArray();
Arrays.sort(keys);
StringBuffer temp = new StringBuffer();
boolean first = true;
for (Object key : keys) {
if (first) {
first = false;
} else {
temp.append("&");
}
temp.append(key).append("=");
Object value = params.get(key);
String valueString = "";
if (null != value) {
valueString = String.valueOf(value);
}
if (encode) {
temp.append(URLEncoder.encode(valueString, "UTF-8"));
} else {
temp.append(valueString);
}
}
return MD5Utils.getMD5(temp.toString()).toUpperCase();
}The overall goal of this design is to minimize the exposure of plaintext credentials, ensure that each request is authenticated and authorized, and protect data transmission through encryption and signature verification.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
