令牌获取与认证机制详解
1. 判断本地 token 是否过期
解析
避免每次都去认证服务器申请新 token。
本地缓存 token,并在快到期时才刷新。
long now = System.currentTimeMillis(); if (cachedToken != null && now < expiresAtMillis - 60_000L) {return cachedToken; }
2. 组装认证请求参数与请求头
解析
构造向认证服务器申请 token 所需参数(如 client_id、client_secret)。
头信息声明请求体为 JSON。
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); Map<String, String> params = new HashMap<>(); params.put("grant_type", "client_credentials"); params.put("client_id", "your_client_id"); params.put("client_secret", "your_secret");
3. 发送 POST 请求获取令牌
解析
用 RestTemplate 向 token 接口发送请求,获取认证信息。
HttpEntity<Map<String, String>> entity = new HttpEntity<>(params, headers); ResponseEntity<String> resp = restTemplate.postForEntity(tokenUrl, entity, String.class); String respJson = resp.getBody();
4. 解析令牌信息并缓存
解析
解析 JSON 拿到 access_token、过期时间等关键信息。
本地保存,方便下次使用。
JSONObject obj = JSON.parseObject(respJson); cachedToken = obj.getString("access_token"); expiresAtMillis = now + obj.getLongValue("expires_in") * 1000; return cachedToken;
完整示例代码
public synchronized String getToken() {long now = System.currentTimeMillis();if (cachedToken != null && now < expiresAtMillis - 60_000L) {return cachedToken;}// 1. 组装认证参数和请求头HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);Map<String, String> params = new HashMap<>();params.put("grant_type", "client_credentials");params.put("client_id", "your_client_id");params.put("client_secret", "your_secret");// 2. 发起 POST 请求HttpEntity<Map<String, String>> entity = new HttpEntity<>(params, headers);ResponseEntity<String> resp = restTemplate.postForEntity(tokenUrl, entity, String.class);String respJson = resp.getBody();// 3. 解析 access_token 并缓存JSONObject obj = JSON.parseObject(respJson);cachedToken = obj.getString("access_token");expiresAtMillis = now + obj.getLongValue("expires_in") * 1000;return cachedToken;
}