有必要限制通过SMS重新发送代码的能力



我需要检查用户是否每30秒重新请求发送短信超过一次,我需要返回一个错误,该操作执行得太频繁,剩余的时间直到下一次发送。

控制器本身

@PostMapping("/resend/sms")
@PreAuthorize("hasAuthority('ROLE_ADMIN') or hasAuthority('SCOPE_trusted')")
public Mono<UserDTO> trustedResendRegistrationSms(
@Validated @RequestBody RegistrationDTO registrationDTO,) {
return accountService.resendRegistrationSms(registrationDTO.getLogin());
}

您可以在控制器bean中通过一些用户指纹注册用户请求,并在30秒内或在某些特殊情况下中断请求。

这是我的例子,

package com.example.app.rest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
@RestController
@RequestMapping(value = "/request-limited/")
public class RequestLimitedController {
// Store user request in set inside the bean
private Set<UserRequest> requests = new HashSet<>();
private static class UserRequest {
public String userFingerprint; // we will use user ip as a fingerprint
public LocalDateTime lastRequestTime = LocalDateTime.now();
public Long count = 0L; // not used in this example, but you can limit the max number of request from the same ip
public UserRequest(String userFingerprint) {
this.userFingerprint = userFingerprint;
}
}

@GetMapping("frequency-sensitive-request")
public ResponseEntity<Object> processFrequencySensitiveRequest(HttpServletRequest httpRequest) {
// First, remove expired requests from set
requests = requests.stream()
.filter( entry -> entry.lastRequestTime.isAfter(LocalDateTime.now().minusHours(1)) )
.collect(Collectors.toSet());
String userFingerprint = httpRequest.getRemoteAddr();
// Find the last request for this user
UserRequest userRequest = requests.stream().filter( r -> r.userFingerprint.equals(userFingerprint)).findFirst().orElse(null);
if (userRequest!=null && userRequest.lastRequestTime.isAfter(LocalDateTime.now().minusSeconds(30))) {
// if it was within 30 seconds, then throw 403
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
if (userRequest == null) {
// If it doesn't exist then create and register it
userRequest = new UserRequest(userFingerprint);
requests.add(userRequest);
}
// Update count and time
userRequest.count++;
userRequest.lastRequestTime = LocalDateTime.now();
// Process the request here
return ResponseEntity.ok().build();
}
}

最新更新