Spring

spring - 문자 인증 시스템 만들기

블린더르 2019. 3. 17. 23:26

인터넷에서 검색할 수 있는 문자 인증 API 는 유료이거나 사업자 등록증이 필요하기 때문에 개인 프로젝트에서는 사용할 수 없습니다.
문자만 보내는 API 를 이용하여 문자 인증 기능을 만들어 보겠습니다..

문자를 보내는 API는 청기와랩 API 를 사용하겠습니다.
청기와랩 홈페이지에서 가입 후 등록하여 API 키를 발급받으면 됩니다.
처음 등록시 500 포인트를 주어 테스트할 수 있도록 해줍니다. (sms 건당 20 포인트 차감)

프로젝트에 Apache 의 Http Component 라이브러리가 있어야 합니다.
pom.xml 에

    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.3</version>
    </dependency>

를 넣어줍니다.

클라이언트

받는 번호와 인증 번호를 입력하여 ajax를 이용해 서버로 전송하는 페이지 입니다.

<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <title>문자 인증</title>
  </head>
  <body>
    <input type="text" name="phone" id="phone" placeholder="받는 사람 번호" />
    <button onclick="sendSms();">전송</button>
    <br />
    <br />
    <input type="text" name="sms" id="sms" placeholder="인증 번호 입력" />
    <button onclick="phoneCheck();">인증</button>

    <script>
      function sendSms() {
        $.ajax({
          url: "<%=request.getContextPath()%>/sendSms",
          data: {
            receiver: $("#phone").val()
          },
          type: "post",
          success: function(result) {
            if (result == "true") {
              console.log(result);
            } else {
              alert("인증번호 전송 실패");
            }
          }
        });
      }

      function phoneCheck() {
        $.ajax({
          url: "<%=request.getContextPath()%>/smsCheck",
          type: "post",
          data: {
            code: $("#sms").val()
          },
          success: function(result) {
            if (result == "ok") {
              alert("번호 인증 성공");
            } else {
              alert("번호 인증 실패");
            }
          }
        });
      }
    </script>
  </body>
</html>

서버

서버에서 문자를 보내는 메소드 입니다.

 @ResponseBody
 @RequestMapping("/sendSms")
 public String sendSms(String receiver) {

        // 6자리 인증 코드 생성
        int rand = (int) (Math.random() * 899999) + 100000;

        // 인증 코드를 데이터베이스에 저장하는 코드는 생략했습니다.

        // 문자 보내기 
        String hostname = "api.bluehouselab.com";
        String url = "https://" + hostname + "/smscenter/v1.0/sendsms";

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(hostname, 443, AuthScope.ANY_REALM),

        // 청기와랩에 등록한 Application Id 와 API key 를 입력합니다.
        new UsernamePasswordCredentials("Application Id", "API key"));

        AuthCache authCache = new BasicAuthCache();
        authCache.put(new HttpHost(hostname, 443, "https"), new BasicScheme());

        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        context.setAuthCache(authCache);

        DefaultHttpClient client = new DefaultHttpClient();

        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-type", "application/json; charset=utf-8");

            //문자에 대한 정보
            String json = "{\"sender\":\"보내는 사람\",\"receivers\":[\"" + receiver
                        + "\"],\"content\":\"문자 내용\"}";

            StringEntity se = new StringEntity(json, "UTF-8");
            httpPost.setEntity(se);

            HttpResponse httpResponse = client.execute(httpPost, context);

            InputStream inputStream = httpResponse.getEntity().getContent();
            if (inputStream != null) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String line = "";
                while ((line = bufferedReader.readLine()) != null)
                    inputStream.close();
                }
            } catch (Exception e) {
                System.err.println("Error: " + e.getLocalizedMessage());
            } finally {
                client.getConnectionManager().shutdown();
            }
            return "true";
        } else {
            return "false";
        }
    }

확인할 정보

  1. Application Id 와 API key 입력 확인
  2. 전송될 문자 정보 확인 (번호, 문자 내용)

입력한 번호가 저장된 코드와 맞는지 확인하는 메소드 입니다.

    @ResponseBody
    @RequestMapping("/smsCheck")
    public String smsCheck(String code) {

        String saveCode = //데이터베이스에 저장된 코드 불러오기

        if(code.equals(saveCode) {
            return "ok";
        }else {
            return "no";
        }
    }

이렇게 문자 인증을 구현해 보았습니다.

참고 자료

청기와랩 SMS Open API
청기와랩 깃허브

반응형