Spring Boot集成google Authenticator实现mfa
liuian 2024-12-04 13:46 53 浏览
1.什么时候mfa?
多重身份验证(MFA)是多步骤的账户登录过程,它要求用户输入更多信息,而不仅仅是输入密码。例如,除了密码之外,用户可能需要输入发送到其电子邮件的代码,回答一个秘密问题,或者扫描指纹。如果系统密码遭到泄露,第二种形式的身份验证有助于防止未经授权的账户访问。
为什么有必要进行多重身份验证?
数字安全在当今世界至关重要,因为企业和用户都在网上存储敏感信息。每个人都使用在线账户与存储在互联网上的应用程序、服务和数据进行交互。这些在线信息的泄露或滥用可能会在现实世界中造成严重后果,例如财务盗窃、业务中断和隐私泄露。 虽然密码可以保护数字资产,但仅仅有密码是不够的。专家级网络犯罪分子试图主动寻找密码。通过发现一个密码,就有可能获得对您可能重复使用该密码的多个账户的访问权限。多重身份验证作为额外的安全层,即使密码被盗,也可以防止未经授权的用户访问这些账户。企业使用多重身份验证来验证用户身份,并为授权用户提供快速便捷的访问。
2.什么是google authenticator?
Google Authenticator是谷歌推出的一款动态口令工具谷歌身份验证器,解决大家的Google账户遭到恶意攻击的问题,在手机端生成动态口令后,在Google相关的服务登陆中除了用正常用户名和密码外,需要输入一次动态口令才能验证成功,即时验证更安全。 Google Authenticator的实现原理是基于服务器端随机生成的密钥,客户端(Authentictor)使用服务器端的密钥和时间戳通过算法生成动态验证码。该验证码的生成只跟密钥和时间戳有关,客户端在飞行模式下都是可以运行的,跟网络等无关。
安装身份验证器
- IOS 版本:Google Authenticator 可以在App Store搜索google authenticator
- 安卓:Google Authenticator
3.代码工程
实验目标
实验用利用google Authenticator进行2次校验
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot-demo</artifactId>
<groupId>com.et</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>MFA</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.12</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.2.220</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>注册并返回二次校验密钥
package com.et.mfa.controller;
import com.et.mfa.domain.User;
import com.et.mfa.service.UserService;
import org.apache.commons.codec.binary.Base32;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(value = "/user/", method = RequestMethod.POST)
public class UserRestController {
@Value("${2fa.enabled}")
private boolean isTwoFaEnabled;
@Autowired
private UserService userService;
@PostMapping("/register/{login}/{password}")
public String register(@PathVariable String login, @PathVariable String password) {
User user = userService.register(login, password);
String encodedSecret = new Base32().encodeToString(user.getSecret().getBytes());
// This Base32 encode may usually return a string with padding characters - '='.
// QR generator which is user (zxing) does not recognize strings containing symbols other than alphanumeric
// So just remove these redundant '=' padding symbols from resulting string
return encodedSecret.replace("=", "");
}
}登陆和二次校验
package com.et.mfa.controller;
import com.et.mfa.domain.AuthenticationStatus;
import com.et.mfa.domain.User;
import com.et.mfa.service.TotpService;
import com.et.mfa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Optional;
@RestController
@RequestMapping(value = "/authenticate/", method = RequestMethod.POST)
public class AuthenticationRestController {
@Value("${2fa.enabled}")
private boolean isTwoFaEnabled;
@Autowired
private UserService userService;
@Autowired
private TotpService totpService;
@PostMapping("{login}/{password}")
public AuthenticationStatus authenticate(@PathVariable String login, @PathVariable String password) {
Optional<User> user = userService.findUser(login, password);
if (!user.isPresent()) {
return AuthenticationStatus.FAILED;
}
if (!isTwoFaEnabled) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(login, password);
SecurityContextHolder.getContext().setAuthentication(authentication);
return AuthenticationStatus.AUTHENTICATED;
} else {
SecurityContextHolder.getContext().setAuthentication(null);
return AuthenticationStatus.REQUIRE_TOKEN_CHECK;
}
}
@GetMapping("token/{login}/{password}/{token}")
public AuthenticationStatus tokenCheck(@PathVariable String login, @PathVariable String password, @PathVariable String token) {
Optional<User> user = userService.findUser(login, password);
if (!user.isPresent()) {
return AuthenticationStatus.FAILED;
}
if (!totpService.verifyCode(token, user.get().getSecret())) {
return AuthenticationStatus.FAILED;
}
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user.get().getLogin(), user.get().getPassword(), new ArrayList<>());
SecurityContextHolder.getContext().setAuthentication(authentication);
return AuthenticationStatus.AUTHENTICATED;
}
@PostMapping("/logout")
public void logout() {
SecurityContextHolder.clearContext();
}
}service
package com.et.mfa.service;
import com.et.mfa.domain.User;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class UserService {
private static final List<User> users = new ArrayList<>();
private static final int SECRET_SIZE = 10;
@Value("${2fa.enabled}")
private boolean isTwoFaEnabled;
public User register(String login, String password) {
User user = new User(login, password, generateSecret());
users.add(user);
return user;
}
public Optional<User> findUser(String login, String password) {
return users.stream()
.filter(user -> user.getLogin().equals(login) && user.getPassword().equals(password))
.findFirst();
}
private String generateSecret() {
return RandomStringUtils.random(SECRET_SIZE, true, true).toUpperCase();
}
}package com.et.mfa.service;
import com.et.mfa.domain.TOTP;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.binary.Hex;
import org.springframework.stereotype.Service;
@Service
public class TotpService {
public boolean verifyCode(String totpCode, String secret) {
String totpCodeBySecret = generateTotpBySecret(secret);
return totpCodeBySecret.equals(totpCode);
}
private String generateTotpBySecret(String secret) {
// Getting current timestamp representing 30 seconds time frame
long timeFrame = System.currentTimeMillis() / 1000L / 30;
// Encoding time frame value to HEX string - requred by TOTP generator which is used here.
String timeEncoded = Long.toHexString(timeFrame);
String totpCodeBySecret;
try {
// Encoding given secret string to HEX string - requred by TOTP generator which is used here.
char[] secretEncoded = (char[]) new Hex().encode(secret);
// Generating TOTP by given time and secret - using TOTP algorithm implementation provided by IETF.
totpCodeBySecret = TOTP.generateTOTP(String.copyValueOf(secretEncoded), timeEncoded, "6");
} catch (EncoderException e) {
throw new RuntimeException(e);
}
return totpCodeBySecret;
}
}
前台页面
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1, shrink-to-fit=no" name="viewport">
<!-- Bootstrap CSS -->
<link crossorigin="anonymous" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css"
integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" rel="stylesheet">
<link href="styles.css" rel="stylesheet"/>
<title>Register</title>
</head>
<body>
<div class="custom-container container">
<h2 align="center">Register user</h2>
<div class="form-group">
<label for="login">Login</label>
<input class="form-control" id="login" placeholder="Enter login" type="text"/>
</div>
<div class="form-group">
<label for="password">Password: </label>
<input class="form-control" id="password" placeholder="Enter password" type="password"/>
</div>
<button class="btn btn-primary" id="btnRegister" type="button">Register</button>
<button class="btn btn-outline-primary" id="btnCancelRegister" type="button">Cancel</button>
</div>
<div class="modal fade" id="modalRegister" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Configure your token</h5>
<button aria-label="Close" class="close" data-dismiss="modal" type="button">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>
To complete registration you should configure your token in Google Authenticator application. You
will need this token further to be able to log in.
</p>
<p>Scan the QR-code diplayed below or enter token manually.</p>
<div class="text-center">
<img class="img-thumbnail" id="tokenQr" src=""/>
<h3><span id="tokenValue"></span></h3>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-dismiss="modal" id="btnRegisterDone" type="button">Done</button>
</div>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script crossorigin="anonymous"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script crossorigin="anonymous"
integrity="sha384-a5N7Y/aK3qNeh15eJKGWxsqtnX/wWdSZSKp+81YjTmS15nvnvxKHuzaWwXHDli+4"
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js"></script>
<script src="scripts.js" type="application/javascript"></script>
</body>
</html>login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1, shrink-to-fit=no" name="viewport">
<!-- Bootstrap CSS -->
<link crossorigin="anonymous" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css"
integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" rel="stylesheet">
<link href="styles.css" rel="stylesheet"/>
<title>Login</title>
</head>
<body>
<div class="custom-container container">
<h2 align="center">Login</h2>
<div class="alert alert-danger collapse" id="msgLoginFailed" role="alert">
Provided login or password could not be recognized
</div>
<div class="form-group">
<label for="login">Login</label>
<input class="form-control" id="login" placeholder="Enter login" type="text"/>
</div>
<div class="form-group">
<label for="password">Password: </label>
<input class="form-control" id="password" placeholder="Enter password" type="password"/>
</div>
<button class="btn btn-primary" id="btnLogin" type="button">Login</button>
<button class="btn btn-outline-primary" id="btnCancelLogin" type="button">Cancel</button>
</div>
<div class="modal fade" id="modalLoginCheckToken" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Verify your token</h5>
<button aria-label="Close" class="close" data-dismiss="modal" type="button">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="alert alert-danger collapse" id="msgTokenCheckFailed" role="alert">
Provided token could not be recognized
</div>
<p>
To complete login you should verify your token generated in Google Authenticator application.
Please, enter the currently generated token to the field below
</p>
<div class="text-center">
<input id="loginToken" placeholder="Enter token" type="text"/>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" id="btnTokenVerify" type="button">Verify</button>
<button class="btn btn-secondary" data-dismiss="modal" type="button">Cancel</button>
</div>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="http://code.jquery.com/jquery.js"></script>
<script crossorigin="anonymous"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script crossorigin="anonymous"
integrity="sha384-a5N7Y/aK3qNeh15eJKGWxsqtnX/wWdSZSKp+81YjTmS15nvnvxKHuzaWwXHDli+4"
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js"></script>
<script src="scripts.js" type="application/javascript"></script>
</body>
</html>以上只是一些关键代码,所有代码请参见下面代码仓库
代码仓库
- https://github.com/Harries/springboot-demo(mfa)
4测试
启动Spring Boot应用
注册
绑定密钥
登陆
二次交验
5.引用
- https://safety.google/authentication/
- http://www.liuhaihua.cn/archives/711268.html
- https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&hl=zh
相关推荐
- 联想windows7笔记本怎么连接网络
-
检查笔记本的无线网卡驱动1.右键我的电脑,点击“属性”,选择左侧“设备管理器”2.点击“网络适配器”,如果方框内没有驱动,请下载驱动精灵万能网卡版安装网卡驱动 二、若发现驱动前面是感叹号的&...
- 淘宝电脑版网页入口(淘宝网电脑版网页官方)
-
网站地址:https://www.taobao.com/网站链接:进入网站服务器IP:116.253.191.241网站描述:淘宝网首页,淘宝网-亚洲最大、最安全的网上交易平台,提供各类服饰、美容...
- 大学生用哪个牌子的笔记本电脑好
-
荣耀MagicBook14英寸轻薄窄边框笔记本电脑(AMD锐龙58G512GFHDIPS正版Office)冰河银这款的性价比较高。也可以根据自己的预算选同系列其他型号。...
- 免费手机模拟器(免费手机模拟器下载)
-
目前能成功在电脑上模拟苹果系统的iOS模拟器,对比市面上常见的安卓模拟器少太多了,主要原因还是iOS系统比较封闭,难于开发。虽然前面说开发很困难,但是国内还是有一些厉害的IT小组成功推出了iOS模拟器...
- 新手怎么制作word表格(工作表格制作)
-
步骤如下:1、本次演示使用的软件为word文字处理软件,软件版本为Microsoftoffice家庭和学生版2016。2、首先打开Excel电子表格,根据问题描述,我们在word中插入两页表格。3、...
-
- 电脑开机启动进不了系统怎么办
-
一、修复错误如果频繁无法正常进入系统,则开机后马上按F8,看能否进入安全模式或最后一次配置正确模式,如能则进入后会自动修复注册表,并回忆前几次出现不正常现象时进行了什么操作,并根据怀疑是某个应用软件导致问题产生,将其卸载,然后正常退出,...
-
2026-01-02 13:05 liuian
- win11任务栏隐藏不了(win11任务栏怎么隐藏)
-
方法/步骤: 1、打开电脑桌面,双击我的计算机。 2、打开控制面板。 3、点击类别切换到大图标或小图标。 4、找到通知区域图标打开。 5、选择显示图标或隐藏图标也可以仅显示通知,选好以后点击...
- 笔记本注册表编辑器怎么打开
-
你好,要打开注册表编辑器,可以按照以下步骤进行操作:1.打开“运行”对话框。可以通过按下Win+R键组合,或者在开始菜单中搜索“运行”来打开。2.在“运行”对话框中,输入“regedit”并点...
- 怎样查询ip地址(怎么顺着ip地址找人)
-
答:查看ip地址的步骤如下,1.通过网页进行查询:可以通过第三方平台进行查询。2.通过电脑内部的网络连接进行查询:首先我们点击桌面右下角的开始,在开始的选项栏当中找到运行,点击运行,然后再用新的对...
- windows server 2003的应用(win2003应用程序服务器)
-
WindowsServer2003支持FAT16、FAT32和NTFS文件系统,同时也支持CDFS(光盘文件系统)和UDF(通用磁盘格式)。NTFS文件系统的安全性高于FAT文件系统,支持域的管理...
- c盘格式化恢复软件(格式化c盘 软件)
-
点我名字,然后点“他的空间”,我的空间有各种恢复软件的详细介绍、下载地址以及使用说明。C盘格式化后需重装操作系统,系统装好后,要恢复其他盘的软件的话可以在格式化C盘前将桌面数据备份在其他盘,重装完成后...
- 一周热门
- 最近发表
- 标签列表
-
- python判断字典是否为空 (50)
- crontab每周一执行 (48)
- aes和des区别 (43)
- bash脚本和shell脚本的区别 (35)
- canvas库 (33)
- dataframe筛选满足条件的行 (35)
- gitlab日志 (33)
- lua xpcall (36)
- blob转json (33)
- python判断是否在列表中 (34)
- python html转pdf (36)
- 安装指定版本npm (37)
- idea搜索jar包内容 (33)
- css鼠标悬停出现隐藏的文字 (34)
- linux nacos启动命令 (33)
- gitlab 日志 (36)
- adb pull (37)
- python判断元素在不在列表里 (34)
- python 字典删除元素 (34)
- vscode切换git分支 (35)
- python bytes转16进制 (35)
- grep前后几行 (34)
- hashmap转list (35)
- c++ 字符串查找 (35)
- mysql刷新权限 (34)
