基于缓存注解的时间戳令牌防重复提交设计

一,概述

API接口由于需要供第三方服务调用,所以必须暴露到外网,并提供了具体请求地址和请求参数。为了防止重放攻击必须要保证请求仅一次有效

比较成熟的做法有批量颁发时间戳令牌,每次请求消费一个令牌

二,实现过程

下面我们基于本地缓存caffeine来说明具体实现。

1、引入pom依赖


		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
		</dependency>
		
		<!-- caffeine依赖 -->
		<dependency>
			<groupId>com.github.ben-manes.caffeine</groupId>
			<artifactId>caffeine</artifactId>
		</dependency>

2、定义缓存管理


import java.util.concurrent.TimeUnit;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.github.benmanes.caffeine.cache.Caffeine;

/**
 * 
 * CacheConfig
 * 
 * @author 00fly
 * @version [版本号, 2019年12月18日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Configuration
public class CacheConfig extends CachingConfigurerSupport
{
    @Bean
    @Override
    public CacheManager cacheManager()
    {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        // 方案一(常用):定制化缓存Cache
        cacheManager.setCaffeine(Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES).initialCapacity(100).maximumSize(10000));
        // 如果缓存种没有对应的value,通过createExpensiveGraph方法同步加载 buildAsync是异步加载
        // .build(key -> createExpensiveGraph(key))
        
        // 方案二:传入一个CaffeineSpec定制缓存,它的好处是可以把配置方便写在配置文件里
        // cacheManager.setCaffeineSpec(CaffeineSpec.parse("initialCapacity=50,maximumSize=500,expireAfterWrite=5s"));
        return cacheManager;
    }
}

3、时间戳服务类

注意:一定要理解为什么使用SpringContextUtils


import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.LongStream;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.fly.core.utils.SpringContextUtils;

/**
 * TimestampService
 */
@Service
public class TimestampService
{
    /**
     * 批量获取用户timestamp,支持缓存
     */
    @Cacheable(value = "timestamp", key = "#user", unless = "#result.size()==0")
    public List<Long> batchGet(String user)
    {
        String userId = DigestUtils.md5DigestAsHex(user.getBytes(StandardCharsets.UTF_8));
        if (StringUtils.isBlank(userId))
        {
            throw new RuntimeException("用户不存在");
        }
        return LongStream.range(0, 10).map(i -> System.currentTimeMillis() + i).collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
    }
    
    /**
     * 判断用户timestamp是否有效
     */
    public boolean isFirstUse(String user, Long timestamp)
    {
        // 注意:缓存基于代理实现,直接调用,缓存机制会失效
        TimestampService timestampService = SpringContextUtils.getBean(TimestampService.class);
        List<Long> data = timestampService.batchGet(user);
        boolean isFirstUse = data.contains(timestamp);
        if (isFirstUse)
        {
            timestampService.removeThenUpdate(user, timestamp);
        }
        return isFirstUse;
    }
    
    /**
     * 移除用户已使用的timestamp,刷新缓存
     * 
     */
    @CachePut(value = "timestamp", key = "#user")
    public List<Long> removeThenUpdate(String user, Long timestamp)
    {
        // 注意:缓存基于代理实现,直接调用,缓存机制会失效
        TimestampService timestampService = SpringContextUtils.getBean(TimestampService.class);
        List<Long> data = timestampService.batchGet(user);
        data.remove(timestamp);
        if (data.size() < 5) // 及时补充
        {
            data.addAll(batchGet(user));
        }
        return data;
    }
}

4、模拟测试接口


import java.util.Collections;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fly.core.entity.JsonResult;
import com.fly.openapi.service.TimestampService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(tags = "接口辅助")
@RestController
@RequestMapping("/auto/help")
public class AutoHelpController
{
    @Autowired
    TimestampService timestampService;
    
    @ApiOperation("批量获取用户timestamp")
    @GetMapping("/getBatchTimestamps")
    public JsonResult<?> getBatchTimestamps(@RequestParam String user)
    {
        log.info("getBatchTimestamps for {}", user);
        return JsonResult.success(Collections.singletonMap("timestamps", timestampService.batchGet(user)));
    }
    
    @ApiOperation("消费timestamp")
    @GetMapping("/useTimestamp")
    public JsonResult<?> useTimestamp(@RequestParam String user, Long timestamp)
    {
        log.info("useTimestamp for {}", user);
        return JsonResult.success(Collections.singletonMap("isFirstUse", timestampService.isFirstUse(user, timestamp)));
    }
}

三,测试过程

1, 模拟批量获取

输入用户名00fly
在这里插入图片描述

2, 消费令牌

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

四,源码放送

https://gitcode.com/00fly/springboot-openapi

git clone https://gitcode.com/00fly/springboot-openapi.git

五,优化方向

  1. 批量获取令牌可采用https、tcp、grpc等更加安全的协议获的
  2. 获取令牌可以考虑采用非对称加密算法鉴权
  3. 多实例部署,可切换到分布式缓存,如redis

有任何问题和建议,都可以向我提问讨论,大家一起进步,谢谢!

-over-

  • 17
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
自定义注解AOP重复提交是一种通过在代码中添加自定义注解的方式来实现重复提交的功能。这种方法可以有效地避免代码耦合性过强,提高代码的可读性和可维护性。 具体实现的方案可以有多种,以下是几种常见的方案: 1. Token验证:在每次请求中添加一个唯一的Token标识,服务端接收到请求后将Token保存在缓存中,然后进行重复提交的验证。如果同一个Token已经存在于缓存中,则表示该请求已经被处理过,可以拒绝重复提交。 2. 请求参数验证:通过对请求参数进行校验,判断是否已经存在相同的请求参数,如果存在则表示重复提交。可以使用缓存或者数据库来存储已经处理过的请求参数,通过查询来进行重复提交的验证。 3. 时间窗口验证:通过设置一个时间窗口,限制在该时间窗口内只接受一次请求。可以使用缓存或者数据库记录请求时间戳,每次接收到请求时与最近一次的时间戳进行比对,如果在时间窗口内已经存在过请求,则拒绝重复提交。 以上方案都可以使用Redis作为缓存来进行存储和验证操作。可以通过引入相关的依赖来使用Spring Boot集成的Redis组件和Jedis依赖。 通过使用自定义注解AOP来实现重复提交可以有效地提高代码的可读性和可维护性,同时也能够减轻服务器的负载,避免因为重复提交而导致的服务器宕机等问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值