Skip to content

十五分钟了解Daming

Yugang Zhou edited this page Jun 13, 2019 · 7 revisions

我们将协助您在15分钟内使用Daming搭建一个短信验证的微服务。

前置准备

  1. 一个空白的Spring Boot 2项目,您可以使用Initializer快速搭建一个
  2. 依赖管理工具,假设您使用的是gradle
  3. 一个本地的Redis实例
  4. 签发JWT所需的私钥,可以自行制作,也可以拷贝本项目源码中的私钥(仅用作演示,请勿使用在生产用途)
  5. 你最喜欢的IDE,例如IntelliJ IDEA

安装并配置Daming

  1. 安装
    您可以从Maven Central获得Daming的最新版本:Maven Central,使用gradle安装Daming
compile "com.github.hippoom:sms-verification-starter:${latestVersion}"

# 使用 spring-data-redis 2.x 
compile "org.springframework.data:spring-data-redis:2.1.2.RELEASE"
  1. 配置
    由于还需要一些简单的配置,指导Daming如何工作,在spring-boot项目中,可以使用profile或环境变量来注入配置项:
# src/main/resources/application.properties

# 设置验证码用途
daming.sms.verification.scope.valid=DEMO

# 设置校验成功后签发JWT时使用的私钥
daming.jwt.key.file=/home/your-app/sms-verification-private.der 
  1. 启动应用 Daming已经准备就绪,启动您的spring-boot应用!

请求发送验证码

打开终端,使用Daming内置的API请求验证码:

curl -v -H 'Content-Type:application/json;charset=UTF-8' -XPOST localhost:8080/api/sms/verification/code -d '{"mobile": "your-mobile-phone-number", "scope": "DEMO"}'

默认情况下,Daming并不会真的发送短信,而是在日志中输出:

c.t.d.sms.SmsVerificationCodeSenderStub  : Sending [DEMO] code 262843 to [your-mobile-phone-number], the code is expiring in PT1M

取其中code后的6位数字待用。

校验验证码

打开终端,使用Daming内置的API校验验证码:

curl -v -H 'Content-Type:application/json;charset=UTF-8' -XDELETE localhost:8080/api/sms/verification/code -d '{"mobile": "your-mobile-phone-number", "scope": "DEMO", "code": "the code"}'

应该会得到如下响应:

{"token":"eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ2ZXJpZmllZE1vYmlsZVBob25lTnVtYmVyIiwibW9iaWxlIjoiMTM5MTc3Nzc3NjMiLCJzY29wZSI6IkRFTU8iLCJleHAiOjE1NjAyNjgzNjV9.hAmB725zVor3mu0lCNlyIjdvnmaRhFmoVRdJUUUMHEEXFo2lBRTlV_1Te02Br0_Juz8gnpAW-8rtVptaFV3fIYogd-T4pVQw4ahXnWV7u_pOkLZLdvOg38v2WRL6YOYDAF1EoFqJU5unnG6bgCFY3dfQFOuggExyPoUUV6ZLh7pvNuDz-fhGzjH9fVrpC9zuxjUU_EHxXxqGg-FTyB9cprqorNdYUvoHJcWSeGUjvVhiSMdn_QqetYFECPyWsFaL7uDtNbBP3ePD-17jcJg_QG1S9mwtnOaD4tNgR0muKbzxoNP7Wzn6BpuQ0dKk-aLzJ5sIMcJ_ZFa5ysB1mDTCRA"}

如果使用JWT验证工具解析该token(如果没有现成的工具,可使用https://jwt.io/),应该会得到

{
  "sub": "verifiedMobilePhoneNumber",
  "mobile": "your-mobile-phone-number",
  "scope": "DEMO",
  "exp": 1560268365
}

它表示Daming已验证该mobile对于scope有效,该token在exp前有效。

进一步阅读

如您所见,仅仅简单的几行配置,就可以启动一个短信验证服务。 另一方面,如果您有以下疑惑:

  1. 请求验证码时要求的scope是用来做什么的?请参考这里
  2. 为什么要签发JWT?请参考这里
  3. 如何集成短信供应商?请参考这里
  4. 我能为单体应用嵌入Daming吗?请参考这里

Clone this wiki locally