我正在开发Sping Boot REST API,它是一个有两个屏幕的移动的应用程序。1.输入电话/联系号码(应使用此输入的号码发送OTP)1.输入OTP进行验证。第一部分已经完成。现在,如果用户输入OTP并且OTP得到验证,那么用户应该无需输入密码就可以登录到系统。那么,我该怎么做呢?
a14dhokn1#
您可以在缓存或cookie中创建jwt标记...在JWT标记中只有userId就足够了。
if (tokenVerify(request.JWTtoken)) { int userId = decodeToken(request.JWTtoken).userId; User user = getUserById(userId); if (user.otp.verify(request.otp)) { user.login(); } }
我会使用这样的伪代码设计。
qc6wkl3g2#
一旦你得到了OTP代码,你应该验证它并创建一个有效的会话令牌。
@RestController @RequestMapping("/auth") public class AuthenticationController { private final Logger log = LoggerFactory.getLogger(AuthenticationController.class); @Autowired private TokenProvider tokenProvider; @Autowired private OtpService otpService; @Autowired private AuthenticationManager authenticationManager; @PostMapping(value = "/authenticate") public ResponseEntity<JWTToken> authorize(@Valid @RequestBody LoginDTO loginDTO) { log.debug("Credentials: {}", loginDTO); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( loginDTO.getUsername(), loginDTO.getPassword()); try { Authentication authentication = this.authenticationManager.authenticate(authenticationToken); String token = tokenProvider.createToken(authentication, loginDTO.isRememberMe()); SecurityContextHolder.getContext().setAuthentication(authentication); return new ResponseEntity<>(new JWTToken(token), HttpStatus.OK); } catch (AuthenticationException exception) { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } } @PostMapping(value = "verify") public ResponseEntity<JWTToken> verifyOtp(@Valid @RequestBody VerifyTokenRequestDTO verifyTokenRequest) { String username = verifyTokenRequest.getUsername(); Integer otp = verifyTokenRequest.getOtp(); Boolean rememberMe = verifyTokenRequest.getRememberMe(); boolean isOtpValid = otpService.validateOTP(username, otp); if (!isOtpValid) { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } String token = tokenProvider.createTokenAfterVerifiedOtp(username, rememberMe); JWTToken response = new JWTToken(token); return new ResponseEntity<>(response, HttpStatus.OK); }
完整来源:https://github.com/hedza06/spring-boot-otp/blob/master/src/main/java/com/starter/springboot/auth/AuthenticationController.java
2条答案
按热度按时间a14dhokn1#
您可以在缓存或cookie中创建jwt标记...在JWT标记中只有userId就足够了。
我会使用这样的伪代码设计。
qc6wkl3g2#
一旦你得到了OTP代码,你应该验证它并创建一个有效的会话令牌。
完整来源:
https://github.com/hedza06/spring-boot-otp/blob/master/src/main/java/com/starter/springboot/auth/AuthenticationController.java