首页 > 其他分享 >服务器接口安全设计之--防止重复提交

服务器接口安全设计之--防止重复提交

时间:2022-12-14 18:36:06浏览次数:49  
标签:令牌 String -- import 接口 token org 服务器 com


这里介绍是通过redis+token 来实现防止重复提交问题。

1. pom文件依赖

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!-- mysql 依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

<!-- SpringBoot 对lombok 支持 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>

<!-- SpringBoot web 核心组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<!-- SpringBoot 外部tomcat支持 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>

<!-- springboot-log4j -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
<version>1.3.8.RELEASE</version>
</dependency>
<!-- springboot-aop 技术 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>

2. redis 的访问类如下:

package com.hou.utils;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class BaseRedisService {

@Autowired
private StringRedisTemplate stringRedisTemplate;

public void setString(String key, Object data, Long timeout) {
if (data instanceof String) {
String value = (String) data;
stringRedisTemplate.opsForValue().set(key, value);
}
if (timeout != null) {
stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
}

public Object getString(String key) {
return stringRedisTemplate.opsForValue().get(key);
}

public void delKey(String key) {
stringRedisTemplate.delete(key);
}

}

3. redis token 类操作:

/**
* 功能说明:
* 功能作者:
* 创建日期:
*/
package com.hou.utils;

import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

// 如何生成token
@Component
public class RedisToken {
@Autowired
private BaseRedisService baseRedisService;
private static final long TOKENTIMEOUT = 60 * 60;

public String getToken() {
// 生成token 规则保证 临时且唯一 不支持分布式场景 分布式全局ID生成规则
String token = "token" + UUID.randomUUID();
// 如何保证token临时 (缓存)使用redis 实现缓存
baseRedisService.setString(token, token, TOKENTIMEOUT);
return token;
}

// 1.在调用接口之前生成对应的令牌(Token), 存放在Redis
// 2.调用接口的时候,将该令牌放入的请求头中
// 3.接口获取对应的令牌,如果能够获取该令牌(将当前令牌删除掉) 就直接执行该访问的业务逻辑
// 4.接口获取对应的令牌,如果获取不到该令牌 直接返回请勿重复提交
public synchronized boolean findToken(String tokenKey) {
// 3.接口获取对应的令牌,如果能够获取该(从redis获取令牌)令牌(将当前令牌删除掉) 就直接执行该访问的业务逻辑
String tokenValue = (String) baseRedisService.getString(tokenKey);
if (StringUtils.isEmpty(tokenValue)) {
return false;
}
// 保证每个接口对应的token 只能访问一次,保证接口幂等性问题
baseRedisService.delKey(tokenValue);
return true;
}
}

4. 注解方式实现token的检查:

package com.hou.ext;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

// 解决接口幂等性 支持网络延迟和表单重复提交
@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtApiIdempotent {
String type();
}
/**
* 功能说明:
* 功能作者:
* 创建日期:
*/
package com.hou.ext;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
*/
// 执行该请求的时候 需要生成令牌 转发到页面进行展示
@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtApiToken {

}
/**

*/
package com.hou.aop;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.itmayeidu.ext.ExtApiIdempotent;
import com.itmayeidu.ext.ExtApiToken;
import com.itmayeidu.utils.ConstantUtils;
import com.itmayeidu.utils.RedisToken;

/**
*/
@Aspect
@Component
public class ExtApiAopIdempotent {
@Autowired
private RedisToken redisToken;

// 1.使用AOP环绕通知拦截所有访问(controller)
@Pointcut("execution(public * com.hou.controller.*.*(..))")
public void rlAop() {
}

// 前置通知
@Before("rlAop()")
public void before(JoinPoint point) {
MethodSignature signature = (MethodSignature) point.getSignature();
ExtApiToken extApiToken = signature.getMethod().getDeclaredAnnotation(ExtApiToken.class);
if (extApiToken != null) {
// 可以放入到AOP代码 前置通知
getRequest().setAttribute("token", redisToken.getToken());
}
}

// 环绕通知
@Around("rlAop()")
public Object doBefore(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

// 2.判断方法上是否有加ExtApiIdempotent
MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
ExtApiIdempotent declaredAnnotation = methodSignature.getMethod().getDeclaredAnnotation(ExtApiIdempotent.class);
// 3.如何方法上有加上ExtApiIdempotent
if (declaredAnnotation != null) {
String type = declaredAnnotation.type();
// 如何使用Token 解决幂等性
// 步骤:
String token = null;
HttpServletRequest request = getRequest();
if (type.equals(ConstantUtils.EXTAPIHEAD)) {
token = request.getHeader("token");
} else {
token = request.getParameter("token");
}

if (StringUtils.isEmpty(token)) {
return "参数错误";
}
// 3.接口获取对应的令牌,如果能够获取该(从redis获取令牌)令牌(将当前令牌删除掉) 就直接执行该访问的业务逻辑
boolean isToken = redisToken.findToken(token);
// 4.接口获取对应的令牌,如果获取不到该令牌 直接返回请勿重复提交
if (!isToken) {
response("请勿重复提交!");
// 后面方法不在继续执行
return null;
}

}
// 放行
Object proceed = proceedingJoinPoint.proceed();
return proceed;
}

public HttpServletRequest getRequest() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
return request;
}

public void response(String msg) throws IOException {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = attributes.getResponse();
response.setHeader("Content-type", "text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();
try {
writer.println(msg);
} catch (Exception e) {

} finally {
writer.close();
}

}

}

5. 在control 中使用如下(非表单提交):

/**
*/
package com.hou.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.hou.ext.ExtApiIdempotent;
import com.hou.utils.ConstantUtils;
import com.hou.utils.RedisToken;
import com.hou.entity.OrderEntity;
import com.hou.mapper.OrderMapper;

/**
*/
@RestController
public class OrderController {

@Autowired
private OrderMapper orderMapper;
@Autowired
private RedisToken redisToken;

// @Autowired
// private RedisTokenUtils redisTokenUtils;
//
// 从redis中获取Token
@RequestMapping("/redisToken")
public String RedisToken() {
return redisToken.getToken();
}

// @RequestMapping(value = "/addOrderExtApiIdempotent", produces =
// "application/json; charset=utf-8")
// @ExtApiIdempotent(type = ConstantUtils.EXTAPIHEAD)
// public String addOrderExtApiIdempotent(@RequestBody OrderEntity
// orderEntity, HttpServletRequest request) {
// // 如何使用Token 解决幂等性
// // 步骤:
// // 2.调用接口的时候,将该令牌放入的请求头中(获取请求头中的令牌)
// String token = request.getHeader("token");
// if (StringUtils.isEmpty(token)) {
// return "参数错误";
// }
// // 3.接口获取对应的令牌,如果能够获取该(从redis获取令牌)令牌(将当前令牌删除掉) 就直接执行该访问的业务逻辑
// boolean isToken = redisToken.findToken(token);
// // 4.接口获取对应的令牌,如果获取不到该令牌 直接返回请勿重复提交
// if (!isToken) {
// return "请勿重复提交!";
// }
// int result = orderMapper.addOrder(orderEntity);
// return result > 0 ? "添加成功" : "添加失败" + "";
// }

@RequestMapping(value = "/addOrderExtApiIdempotent", produces = "application/json; charset=utf-8")
@ExtApiIdempotent(type = ConstantUtils.EXTAPIHEAD)
public String addOrderExtApiIdempotent(@RequestBody OrderEntity orderEntity, HttpServletRequest request) {
int result = orderMapper.addOrder(orderEntity);
return result > 0 ? "添加成功" : "添加失败" + "";
}

}

6 在control 中使用如下(表单提交):

/**
*/
package com.hou.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hou.ext.ExtApiIdempotent;
import com.hou.ext.ExtApiToken;
import com.hou.utils.ConstantUtils;
import com.hou.utils.RedisToken;
import com.hou.entity.OrderEntity;
import com.hou.mapper.OrderMapper;

/**
*/
@Controller
public class OrderPageController {
@Autowired
private OrderMapper orderMapper;
@Autowired
private RedisToken redisToken;

@RequestMapping("/indexPage")
@ExtApiToken
public String indexPage(HttpServletRequest req) {
return "indexPage";
}

@RequestMapping("/addOrderPage")
@ExtApiIdempotent(type = ConstantUtils.EXTAPIFROM)
public String addOrder(OrderEntity orderEntity) {
int addOrder = orderMapper.addOrder(orderEntity);
return addOrder > 0 ? "success" : "fail";
}

}

7.前端部分代码实现如下:

<form action="/addOrderPage" method="post">
<input type="hidden" name="token" value="${token}"> <span>订单名称</span><input
type="text" name="orderName"><br> <span>订单描述</span><input
type="text" name="orderDes"><br> <input type="submit">
</form>

 

标签:令牌,String,--,import,接口,token,org,服务器,com
From: https://blog.51cto.com/u_15461374/5938164

相关文章

  • redis5-cluster 集群搭建
    1、安装环境信息centos7redis52、整体集群信息#以直接在一台机器上实现上述的伪集群,因为端口号特意设置为不同的。#重点:不论机器多少,对于部署过程都是一样的,只不过是在不......
  • 8 多路召回的融合排序
    融合排序:将多种召回排序的列表进行融合为一个列表......
  • 监控报警体系:Prometheus和Grafana
    总体prometheus全链路监控报警,在当今云原生时代可观测领域,Prometheus + Grafana 成为可观测性事实标准。采集数据:运维团队可以使用 Prometheus 监控云原生 Kub......
  • Java基础之变量
    变量变量为可以变化的量。java是一种强类型语言,每个变量都必须声明其类型。Java变量是程序中最基本的存储单位,其要素包括:变量名,变量类型和作用域。 数据类型变量名=......
  • nginx 反向代理多示例----实现Session共享
    关于session共享的方式有多种:(1)通过nginx的ip_hash,根据ip将请求分配到对应的服务器(2)基于关系型数据库存储(3)基于cookie存储(4)服务器内置的session复制域。(5)基于nosq......
  • C# 获取指定固定范围内的比例固定的实际图片大小
    Rectangle?getImageRegion(PictureBoxpic){if(pic.Image==null)returnnull;varpicHeight=pic.Width*p......
  • gameboy GB 第二次机器人大战G 金手指 VBA
    ------------------------------------------------------------------------------------------------------------------------------------------------------------......
  • 基于Sharding-Jdbc 实现的读写分离实现
    1.pom文件依赖<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.2.RELEASE</version......
  • Elasticsearch+Logstash+Kiabana 日志管理
       日志是分析线上问题的重要手段,通常我们会把日志输出到控制台或者本地文件中,排查问题时通过根据关键字搜索本地日志,但越来越多的公司,项目开发中采用分布式的架构,日......
  • HttpURLConnection Authorization 取得问题
    HttpURLConnection.setRequestProperty("Authorization","Y2U0ZDQyY2QtNDE");//设置AuthorizationHttpURLConnection.getRequestProperty("Authorization");//无法取......