{"id":1730,"date":"2023-03-26T19:57:08","date_gmt":"2023-03-26T11:57:08","guid":{"rendered":"https:\/\/www.appblog.cn\/?p=1730"},"modified":"2023-04-23T21:34:09","modified_gmt":"2023-04-23T13:34:09","slug":"spring-boot-access-multifactor-authentication-2fa-mfa","status":"publish","type":"post","link":"https:\/\/www.appblog.cn\/index.php\/2023\/03\/26\/spring-boot-access-multifactor-authentication-2fa-mfa\/","title":{"rendered":"Spring Boot\u63a5\u5165\u591a\u56e0\u5b50\u8ba4\u8bc1\uff082FA|MFA\uff09"},"content":{"rendered":"<h2>\u5ba2\u6237\u7aef<\/h2>\n<ul>\n<li><a target=\"_blank\" rel=\"noopener\" href=\"https:\/\/apps.apple.com\/app\/google-authenticator\/id388497605\">Google Authenticator<\/a><\/li>\n<li><a target=\"_blank\" rel=\"noopener\" href=\"https:\/\/authy.com\/\">Authy<\/a><\/li>\n<li><a target=\"_blank\" rel=\"noopener\" href=\"https:\/\/steptwo.app\/\">Step Two<\/a> <\/li>\n<\/ul>\n<p><!-- more --><\/p>\n<h2>\u6ce8\u610f<\/h2>\n<ul>\n<li>\u670d\u52a1\u7aef\u65f6\u95f4\u5fc5\u987b\u4e0e\u5ba2\u6237\u7aef\u4e00\u81f4<\/li>\n<li>\u63a5\u5165\u81ea\u5df1\u7684\u7528\u6237\u7cfb\u7edf\u65f6\uff0c\u53ef\u4ee5\u8bbe\u8ba1\u4e00\u4e2a user &#8211; secret \u4e00\u4e00\u6620\u5c04\u7684\u8868\u7528\u6765\u7ed1\u5b9a\u8eab\u4efd\u9a8c\u8bc1\u3002\u672c\u6848\u4f8b\u5077\u61d2\u4e86\uff0c\u76f4\u63a5\u653e\u5185\u5b58\u91cc\u7684<\/li>\n<li>\u4e8c\u7ef4\u7801\u7684\u5c55\u793a\u653e\u5728\u4e86 JSON \u4e2d\uff0c\u4f7f\u7528\u4e86\u56fd\u5185\u53ef\u4ee5\u8bbf\u95ee\u7684\u4e00\u4e2a API\uff0c\u53ef\u80fd\u4f1a\u5931\u6548<\/li>\n<\/ul>\n<h2>\u5feb\u901f\u5f00\u59cb<\/h2>\n<ul>\n<li>\u7528\u6237\u4e0b\u8f7d\u3001\u5b89\u88c5\u597d\u5ba2\u6237\u7aef\u5e94\u7528\u540e\uff0c\u5c1d\u8bd5\u53d1\u51fa\u6b64\u8bf7\u6c42<\/li>\n<\/ul>\n<pre><code class=\"language-bash\">curl -XGET localhost:8080\/bind?username=test<\/code><\/pre>\n<ul>\n<li>\n<p>\u5c06\u8fd4\u56de JSON \u4e2d\u7684\u4e8c\u7ef4\u7801\u5730\u5740\u901a\u8fc7\u6d4f\u89c8\u5668\u6253\u5f00\uff0c\u6216\u8005\u4f7f\u7528 wget \u7b49\u5ba2\u6237\u7aef\u4e0b\u8f7d\u5230\u672c\u5730<\/p>\n<\/li>\n<li>\n<p>\u4f7f\u7528\u5ba2\u6237\u7aef\u5bfc\u5165\u6b64\u4e8c\u7ef4\u7801\uff0c\u6216\u8005\u586b\u5199\u5bc6\u6587\u5bfc\u5165\u3002\u5bfc\u5165\u6210\u529f\u540e\uff0c\u5e94\u7528\u4f1a\u51fa\u73b0\u76f8\u5e94\u7684 6 \u4f4d\u6570\u9a8c\u8bc1\u7801<\/p>\n<\/li>\n<li>\n<p>\u5c06\u9a8c\u8bc1\u7801\u4f5c\u4e3a\u4ee5\u4e0b HTTP \u8bf7\u6c42\u7684 codeInput \u5b57\u6bb5\u5185\u5bb9<\/p>\n<\/li>\n<\/ul>\n<pre><code class=\"language-bash\">curl -XGET localhost:8080\/check?username=test&amp;codeInput={codeInput}<\/code><\/pre>\n<ul>\n<li>\u8fd4\u56de\u7684\u7ed3\u679c\u4e3a true \u5219\u9a8c\u8bc1\u6210\u529f<\/li>\n<\/ul>\n<h2>\u4ee3\u7801\u5b9e\u73b0<\/h2>\n<h3>\u5de5\u5177\u7c7b<\/h3>\n<p>MultiFactorAuthenticator.java<\/p>\n<pre><code class=\"language-java\">import lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.codec.binary.Base32;\nimport org.apache.commons.codec.binary.Base64;\n\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\nimport java.security.InvalidKeyException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.SecureRandom;\n\n@Slf4j\npublic class MultiFactorAuthenticator {\n    \/\/ this is the issuer, you can change it to your company\/project name.\n    private static final String ISSUER = &quot;Hello&quot;;\n    \/\/ this is a http api (GET request) to generate the QR code image to show in the website\/app.\n    private static final String IMAGE_QR_CODE_API = &quot;https:\/\/api.qrserver.com\/v1\/create-qr-code\/?size=150x150&amp;data=&quot;;\n    \/\/ you can change it to any string.\n    private static final String SEED = &quot;thisisgoogleauthenticator&quot;;\n    \/\/ taken from Google pam docs - we probably don&#039;t need to mess with these\n    private static final String RANDOM_NUMBER_ALGORITHM = &quot;SHA1PRNG&quot;;\n    private static final int SECRET_SIZE = 10;\n    \/\/ suggest: the smaller the value, the safer it is. (from 1 to 17)\n    private static final int WINDOW_SIZE = 1;\n\n    public static String generateSecretKey() {\n        try {\n            SecureRandom sr = SecureRandom.getInstance(RANDOM_NUMBER_ALGORITHM);\n            sr.setSeed(Base64.decodeBase64(SEED));\n            byte[] buffer = sr.generateSeed(SECRET_SIZE);\n            Base32 codec = new Base32();\n            byte[] bEncodedKey = codec.encode(buffer);\n            return new String(bEncodedKey);\n        } catch (NoSuchAlgorithmException e) {\n            log.error(&quot;generate secret exception\uff1a{[]}&quot;, e);\n        }\n        return null;\n    }\n\n    public static String getQRBarcodeURL(String user, String secret) {\n        String format = IMAGE_QR_CODE_API + &quot;otpauth:\/\/totp\/%s?secret=%s%%26issuer=%s&quot;;\n        String imageUrl = String.format(format, user, secret, ISSUER);\n        log.info(imageUrl);\n        return imageUrl;\n    }\n\n    public static boolean checkCode(String secret, long code, long time) {\n        Base32 codec = new Base32();\n        byte[] decodedKey = codec.decode(secret);\n        \/\/ convert unix msec time into a 30 second &quot;window&quot;\n        \/\/ this is per the TOTP spec (see the RFC for details)\n        long t = (time \/ 1000L) \/ 30L;\n        \/\/ Window is used to check codes generated in the near past.\n        \/\/ You can use this value to tune how far you&#039;re willing to go.\n        for (int i = -WINDOW_SIZE; i &lt;= WINDOW_SIZE; ++i) {\n            long hash;\n            try {\n                hash = verifyCode(decodedKey, t + i);\n            } catch (Exception e) {\n                \/\/ Yes, this is bad form - but\n                \/\/ the exceptions thrown would be rare and a static configuration problem\n                e.printStackTrace();\n                throw new RuntimeException(e.getMessage());\n                \/\/return false;\n            }\n            if (hash == code) {\n                return true;\n            }\n        }\n        \/\/ The validation code is invalid.\n        return false;\n    }\n\n    private static int verifyCode(byte[] key, long t) throws NoSuchAlgorithmException, InvalidKeyException {\n        byte[] data = new byte[8];\n        long value = t;\n        for (int i = 8; i-- &gt; 0; value &gt;&gt;&gt;= 8) {\n            data[i] = (byte) value;\n        }\n        SecretKeySpec signKey = new SecretKeySpec(key, &quot;HmacSHA1&quot;);\n        Mac mac = Mac.getInstance(&quot;HmacSHA1&quot;);\n        mac.init(signKey);\n        byte[] hash = mac.doFinal(data);\n        int offset = hash[20 - 1] &amp; 0xF;\n        \/\/ We&#039;re using a long because Java hasn&#039;t got unsigned int.\n        long truncatedHash = 0;\n        for (int i = 0; i &lt; 4; ++i) {\n            truncatedHash &lt;&lt;= 8;\n            \/\/ We are dealing with signed bytes:\n            \/\/ we just keep the first byte.\n            truncatedHash |= (hash[offset + i] &amp; 0xFF);\n        }\n        truncatedHash &amp;= 0x7FFFFFFF;\n        truncatedHash %= 1000000;\n        return (int) truncatedHash;\n    }\n\n    private MultiFactorAuthenticator() {\n    }\n}<\/code><\/pre>\n<h3>\u63a5\u5165\u81ea\u5df1\u7684\u7528\u6237\u4f53\u7cfb<\/h3>\n<p>TestController.java<\/p>\n<pre><code class=\"language-java\">import com.auth.www.util.MultiFactorAuthenticator;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\n\n\/**\n * Authentication Bind \/ Check Interface\n *\/\n@Slf4j\n@RestController\npublic class TestController {\n\n    \/**\n     * We can use a Map to simulate the database.\n     *\/\n    protected Map&lt;String, String&gt; userSecret = new ConcurrentHashMap&lt;&gt;();\n\n    \/**\n     * Bind user to the secret.\n     *\n     * @param username username\n     * @return qr code\n     *\/\n    @GetMapping(&quot;\/bind&quot;)\n    public Map&lt;String, String&gt; bind(@RequestParam String username) {\n        HashMap&lt;String, String&gt; json = new HashMap&lt;&gt;(4);\n        if (userSecret.containsKey(username)) {\n            String secret = userSecret.get(username);\n            String qrCodeLink = MultiFactorAuthenticator.getQRBarcodeURL(username, secret);\n            json.put(&quot;qrCodeLink&quot;, qrCodeLink);\n            json.put(&quot;user&quot;, username);\n            json.put(&quot;secret&quot;, secret);\n            log.info(userSecret.toString());\n            return json;\n        }\n        String secret = MultiFactorAuthenticator.generateSecretKey();\n        String qrCodeLink = MultiFactorAuthenticator.getQRBarcodeURL(username, secret);\n        json.put(&quot;qrCodeLink&quot;, qrCodeLink);\n        json.put(&quot;user&quot;, username);\n        json.put(&quot;secret&quot;, secret);\n        userSecret.put(username, secret);\n        log.info(userSecret.toString());\n        return json;\n    }\n\n    \/**\n     * check user&#039;s code\n     *\n     * @param username  user name\n     * @param codeInput input from user\n     * @return right or not\n     *\/\n    @GetMapping(&quot;\/check&quot;)\n    public Map&lt;String, Object&gt; check(@RequestParam String username, @RequestParam String codeInput) {\n        HashMap&lt;String, Object&gt; json = new HashMap&lt;&gt;(2);\n        String secret = userSecret.get(username);\n        if (null != codeInput &amp;&amp; codeInput.length() == 6 &amp;&amp; null != secret) {\n            long code = Long.parseLong(codeInput);\n            boolean result = MultiFactorAuthenticator.checkCode(secret, code, System.currentTimeMillis());\n            json.put(&quot;pass&quot;, result);\n        } else {\n            json.put(&quot;pass&quot;, false);\n        }\n        log.info(userSecret.toString());\n        return json;\n    }\n}<\/code><\/pre>\n<h3>\u5355\u5143\u6d4b\u8bd5<\/h3>\n<p>MultiFactorAuthenticatorApplicationTests.java<\/p>\n<pre><code class=\"language-java\">import com.auth.www.util.MultiFactorAuthenticator;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest\npublic class MultiFactorAuthenticatorApplicationTests {\n\n    @Test\n    public void genSecretTest() {\n        String secret = MultiFactorAuthenticator.generateSecretKey();\n        String qrCode = MultiFactorAuthenticator.getQRBarcodeURL(&quot;username&quot;, secret);\n        System.out.println(&quot;secret = &quot; + secret);\n        System.out.println(&quot;qrCode = &quot; + qrCode);\n    }\n\n    @Test\n    public void verifyTest() {\n        String secret = &quot;ABCDEFGHIJKLMN&quot;;\n        String randomCode = &quot;012345&quot;;\n        long code = Long.parseLong(randomCode);\n        boolean result = MultiFactorAuthenticator.checkCode(secret, code, System.currentTimeMillis());\n        System.out.println(result);\n    }\n}<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u5ba2\u6237\u7aef Google Authenticator Authy Step Two \u6ce8\u610f \u670d\u52a1\u7aef\u65f6\u95f4\u5fc5\u987b\u4e0e\u5ba2\u6237\u7aef\u4e00 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[41],"tags":[434],"class_list":["post-1730","post","type-post","status-publish","format-standard","hentry","category-spring-boot","tag-mfa"],"_links":{"self":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/1730","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/comments?post=1730"}],"version-history":[{"count":0,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/1730\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/media?parent=1730"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/categories?post=1730"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/tags?post=1730"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}