这是一个前后端分离的项目 前端用的是Vue框架 后端用的是java 现在的场景是有A和B两端 A端向B端发送请求的时候 会在请求的末尾添加上密钥和当前的时间戳 并且该请求是一个post请求需要请求体 请求体里有具体的信息 比如手机号商户号 A端需要根据密钥和请求体里的信息在前端根据特定的规则生成一个签名发送到B端 B端在接收到请求的时候会使用filter 需要根据相同的规则验证签名是否一致 否则过滤掉该请求 请将上述场景 利用代码实现
时间: 2023-12-14 17:36:01 浏览: 68
【技术栈】前端Vue + 后端Java
5星 · 资源好评率100%
以下是示例代码,其中签名的生成规则为将请求体和时间戳按照一定顺序拼接后进行哈希计算,密钥为示例中的字符串"secret_key":
前端代码:
```javascript
import axios from 'axios';
import md5 from 'js-md5';
const baseUrl = 'http://backend_api_url';
// 生成签名
function generateSignature(data, timestamp) {
const sortedData = Object.keys(data).sort().map(key => `${key}=${data[key]}`).join('&');
const stringToSign = `${sortedData}×tamp=${timestamp}`;
const signature = md5(stringToSign + 'secret_key');
return signature;
}
// 发送请求
function sendRequest(data) {
const timestamp = Math.floor(Date.now() / 1000);
const signature = generateSignature(data, timestamp);
const postData = Object.assign({}, data, { timestamp, signature });
return axios.post(baseUrl, postData);
}
// 调用示例
sendRequest({
phone: '1234567890',
merchant_id: 'abcd1234'
}).then(response => {
console.log(response);
}).catch(error => {
console.error(error);
});
```
后端代码:
```java
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebFilter(filterName = "signatureFilter", urlPatterns = "/*")
public class SignatureFilter implements Filter {
private static final String SECRET_KEY = "secret_key";
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String method = httpRequest.getMethod();
if (!method.equals("POST")) {
chain.doFilter(request, response);
return;
}
Map<String, String[]> parameterMap = new TreeMap<>(httpRequest.getParameterMap());
String timestamp = httpRequest.getParameter("timestamp");
String signature = httpRequest.getParameter("signature");
String sortedParams = parameterMap.keySet().stream()
.sorted()
.map(key -> key + "=" + parameterMap.get(key)[0])
.reduce((a, b) -> a + "&" + b)
.orElse("");
String stringToSign = sortedParams + "×tamp=" + timestamp;
String expectedSignature = md5(stringToSign + SECRET_KEY);
if (signature.equals(expectedSignature)) {
chain.doFilter(request, response);
} else {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
}
@Override
public void destroy() {}
private static String md5(String s) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(s.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
```
阅读全文