AWS SNS-SpringBoot实现发送登陆验证码短信的API

时间:2019-01-31
本文章向大家介绍AWS SNS-SpringBoot实现发送登陆验证码短信的API,主要包括AWS SNS-SpringBoot实现发送登陆验证码短信的API使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

用 SpringBoot 和 AWS的 SNS服务 做了一个发送手机登陆验证码短信的demo。
资源参照: 我在这里.

技术

SpringBoot
AWS-SNS
Swagger2
lombok

要件

非常简单的要件,访问API,向指定的手机号发送一条信息。

通过starter生成模板程序

参照: Gradle的SpringBoot工程.

添加依赖关系

在build.gradle文件内添加依赖关系
AWS的关联依赖关系追加,参照: 将开发工具包与 Gradle 一起使用.
Swagger2的依赖包

// Swagger
  compile 'io.springfox:springfox-swagger2:2.2.2'
  compile 'io.springfox:springfox-swagger-ui:2.2.2'
  compile "com.google.guava:guava:17.0"

lombok的依赖包

compile('org.projectlombok:lombok:1.16.6')

添加配置属性内容

应用属性指定

application.properties内添加端口以及log level指定

server.port=1234
#Log level
logging.level.root=INFO
logging.level.org.springframework.web=INFO

aws及其他内容指定

新作文件 application.yml ,内容为

swaggerui:
  enabled: true

aws:
  common:
    local: true
    credentialFile: awscredential.properties
    region: ap-northeast-1

aws认证信息的指定

新作文件 awscredential.properties,内容为
具体的参数内容,根据自己的测试环境设置,安全上考虑,只为了单体测试,实际的AWS环境上,是由IAM角色控制权限

accessKey = XXXXX
secretKey = XXXXX

AWS认证信息服务

添加AWS认证信息mapping文件

AwsConfiguration.java

@Component
@Data
@ConfigurationProperties(prefix = "aws.common")
public class AwsConfiguration {
    private boolean local;
    private String credentialFile;
    private String region;
}

添加获取AWS认证信息的服务

AwsAuthService.java

@Service
public class AwsAuthService {
    @Autowired
    private AwsConfiguration config;

    public AWSCredentialsProvider getCredentialProvider() {
        if (config.isLocal()) {
            return new ClasspathPropertiesFileCredentialsProvider(config.getCredentialFile());
        } else {
            // It will be controlled by IAM role in aws。
            return null;
        }
    }
}

添加Swagger的服务

AppConfig.java

@Configuration
@EnableSwagger2 // Springfoxを使用可能にするためのアノテーション
public class AppConfig {
  @Autowired
  private SwaggerUIConfig config;

  @Bean
  @SuppressWarnings("unchecked")
  public Docket document() {
    if (!config.isEnabled()) {
      return new Docket(DocumentationType.SWAGGER_2)
          .select()
          .paths(or(containsPattern("/notmatched")))
          .build()
          .apiInfo(new ApiInfoBuilder().build());
    }
    return new Docket(DocumentationType.SWAGGER_2).select().paths(paths()).build()
        .apiInfo(apiInfo());
  }

  @SuppressWarnings("unchecked")
  private Predicate<String> paths() {
    return or(containsPattern("/api*")); //APIのエントリポイントを正規表現で指定
  }

  private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
        .title("SAMPLE SPRING BOOT SECURITY API")
        .description("")
        .termsOfServiceUrl("http://localhost:1234")
        .contact("Powerd by Test.co")
        .version("v1")
        .build();
  }

  @Data
  @Component
  @ConfigurationProperties(prefix = "swaggerui")
  public static class SwaggerUIConfig {
    private boolean enabled;
  }

}

添加验证码生成的服务

IdentifyCodeUtil.java

public class IdentifyCodeUtil {
    public static String getRandom() {
        String num = "";
        for (int i = 0; i < 6; i++) {
            num = num + String.valueOf((int) Math.floor(Math.random() * 9 + 1));
        }
        return num;
    }
}

添加API的Controller文件

SmsVerifityCodeController.java

@RequestMapping(value = "/sendMessage", method = RequestMethod.GET)
    @ApiOperation(value = "Send SMS message.", nickname = "sendSMSMessage")
    public String sendMessage(
            @ApiParam(value = "Telephone Number.", required = true) @RequestParam String phoneNumber) {
        log.debug("phoneNumber:{}", phoneNumber);
        return smsVerifityCodeService.sendSMSMessage(phoneNumber);
    }

添加API的Service文件

SmsVerifityCodeService.java

@Slf4j
@Service
public class SmsVerifityCodeService {

    @Autowired
    private AwsConfiguration awsConfig;
    @Autowired
    private AwsAuthService authService;
    @Autowired
    private AmazonSNS amazonSns;

    @Bean
    private AmazonSNS amazonSnsClient() {
        AmazonSNSClientBuilder builder = AmazonSNSClient.builder();
        builder.withCredentials(authService.getCredentialProvider());
        builder.withRegion(awsConfig.getRegion());
        AmazonSNS client = builder.build();
        return client;
    }

    public String sendSMSMessage(String phoneNumber) {
        //String message = "My SMS message";
        Map<String, MessageAttributeValue> smsAttributes =
                new HashMap<String, MessageAttributeValue>();
        //<set SMS attributes>
        smsAttributes.put("AWS.SNS.SMS.MaxPrice", new MessageAttributeValue()
                .withStringValue("0.50") //Sets the max price to 0.50 USD.
                .withDataType("Number"));

        //get VerifyCode.
        String message = IdentifyCodeUtil.getRandom();

        PublishResult result = amazonSns.publish(new PublishRequest()
                            .withMessage(message)
                            .withPhoneNumber(phoneNumber)
                            .withMessageAttributes(smsAttributes));
        log.info("message ID:{}",result.getMessageId()); // Prints the message ID.
        return "";
    }
}

测试

到此,简单的souce部分已经完成,可以打开界面进行测试了
登陆界面
http://localhost:1234/swagger-ui.html

输入电话号码,测试成功。
✳注意,电话号码的格式为 +国际区号 电话,例 +8613012345678