How to Secure Mobile API Calls with Token and Signature Design

This article explains how to secure mobile app open APIs by enforcing HTTPS, designing request signatures with timestamps and tokens, validating them on the server, and managing token‑UID relationships using Redis, complete with Java code examples for parameter extraction and signature generation.

21CTO
21CTO
21CTO
How to Secure Mobile API Calls with Token and Signature Design

Introduction

When designing open API interfaces for apps, security is crucial because most APIs handle personal and sensitive data. Authentication typically requires users to provide credentials, but exposing plaintext passwords should be minimized. Web projects often store sessions and cookies to maintain user sessions.

How to Validate and Maintain User Login in App APIs

In open APIs, the backend must verify and maintain login validity after user authentication, similar to token verification used by platforms like Taobao and WeChat.

Use HTTPS for Sensitive APIs

HTTPS adds an SSL layer to HTTP, encrypting network communication. It requires an SSL certificate, usually a paid CA certificate.

Signature Design

After a user logs in, the server returns a token. Subsequent requests must include timestamp , token , and a sign generated by sorting all parameters alphabetically, applying MD5 (optionally with salt), and converting to uppercase. Example URL with timestamp and token:

https://www.andy.cn/api/user/update/info.shtml?city=北京×tamp=12445323134&token=wefkfjdskfjewfjkjfdfnc

After adding the signature:

https://www.andy.cn/api/user/update/info.shtml?city=北京×tamp=12445323134&token=wefkfjdskfjewfjkjfdfnc&sign=FDK2434JKJFD334FDF2

This reduces the exposure of plaintext credentials and ensures secure data access.

Implementation Details

1. The client sends username and password; the server validates them. If correct, it returns a unique string (usually a UUID) and stores a token‑UID mapping in Redis for later verification. If incorrect, an error code is returned.

2. Server URL interception rules:

Check for timestamp, token, and sign parameters; reject if missing.

Verify that the request timestamp is within an acceptable window (e.g., 30 minutes).

Validate the token by looking up the UID in Redis; reject if expired.

Recreate the signature from the request parameters and compare it with the provided sign; allow the request if they match.

Only authentication URLs (e.g., login) are exempt from interception; all other URLs are protected.

3. Token‑UID relationship maintenance: create the mapping when a user logs in and delete it when the user logs out.

Signature Generation Code (Java)

Extract all request parameters except sign:

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);
}

Generate 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();
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend Developmenttoken authenticationAPI SecurityHTTPSrequest signing
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.