springboot google验证器

545 阅读1分钟

pom.xml

<dependency>
    <groupId>dev.samstevens.totp</groupId>
    <artifactId>totp-spring-boot-starter</artifactId>
    <version>1.7.1</version>
</dependency>

controller

@PostMapping("/getGoogleAuthInfo")
@ApiOperation(value = "获取google验证信息")
@SneakyThrows
public GoogleAuthenticatorVO getGoogleAuthInfo() {
  String secret = secretGenerator.generate();
  QrData data =
      qrDataFactory.newBuilder().label("username").secret(secret).issuer("appname").build();
  String url =
      Utils.getDataUriForImage(qrGenerator.generate(data), qrGenerator.getImageMimeType());
  return GoogleAuthenticatorVO.builder().secret(secret).url(url).build();
}

@PostMapping("/verifyGoogleAuth")
@ApiOperation(value = "验证google验证器")
public Boolean verifyGoogleAuth(@Validated @RequestBody GoogleAuthenticatorDTO dto) {
  return codeVerifier.isValidCode(dto.getSecret(), dto.getCode());
}

dto,vo没复制了,就2个属性

测试

在google游览器上安装[Authenticator]插件(chrome://extensions/?id=bhghoamapcdpbohphigoooaddinpkbai) ,导入 getGoogleAuthInfo 接口中的秘钥。

verifyGoogleAuth 验证验证码是否正确

image.png

github 代码 web模块

github.com/gray1994102…