Spring Boot集成google Authenticator实现mfa
liuian 2024-12-04 13:46 24 浏览
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
相关推荐
- MySQL合集-mysql5.7及mysql8的一些特性
-
1、Json支持及虚拟列1.1jsonJson在5.7.8原生支持,在8.0引入了json字段的部分更新(jsonpartialupdate)以及两个聚合函数,JSON_OBJECTAGG,JS...
- MySQL 双表架构在房产中介房源管理中的深度实践
-
MySQL房源与价格双表封神:降价提醒实时推送客户房产中介实战:MySQL空间函数精准定位学区房MySQL狠招:JSON字段实现房源标签自由组合筛选房源信息与价格变更联动:MySQL黄金搭档解决客户看...
- MySQL 5.7 JSON 数据类型使用总结
-
从MySQL5.7.8开始,MySQL支持原生的JSON数据类型。MySQL支持RFC7159定义的全部json数据类型,具体的包含四种基本类型(strings,numbers,boolea...
- MySQL 8.0 SQL优化黑科技,面试官都不一定知道!
-
前言提到SQL优化,大多数人想到的还是那些经典套路:建索引、避免全表扫描、优化JOIN顺序…这些确实是基础,但如果你还停留在MySQL5.7时代的优化思维,那就out了。MySQL8.0已经发布好...
- 如何在 MySQL 中使用 JSON 数据(mysql的json函数与实例)
-
在MySQL中学习“NoSQL”MySQL从5.7版本开始就支持JSON格式的数据类型,该数据类型支持JSON文档的自动验证和优化存储和访问。尽管JSON数据最好存储在MongoDB等...
- MySQL中JSON的存储原理(mysql中json字段操作)
-
前言:表中有json字段后,非索引查询性能变得非常糟糕起因是我有一张表,里面有json字段后,而当mysql表中有200w数据的时候,走非索引查询性能变得非常糟糕需要3到5s。因此对mysql的jso...
- mysql 之json字段详解(多层复杂检索)
-
MySQL5.7.8开始支持JSON数据类型。MySQL8.0版本中增加了对JSON类型的索引支持。示例表CREATETABLE`users`(`id`intNOTNULLAU...
- VMware vCenter Server 8.0U3b 发布下载,新增功能概览
-
VMwarevCenterServer8.0U3b发布下载,新增功能概览ServerManagementSoftware|vCenter请访问原文链接:https://sysin.or...
- Spring Boot 3.x 新特性详解:从基础到高级实战
-
1.SpringBoot3.x简介与核心特性1.1SpringBoot3.x新特性概览SpringBoot3.x是建立在SpringFramework6.0基础上的重大版...
- 如何设计Agent的记忆系统(agent记忆方法)
-
最近看了一张画Agent记忆分类的图我觉得分类分的还可以,但是太浅了,于是就着它的逻辑,仔细得写了一下在不同的记忆层,该如何设计和选型先从流程,作用,实力和持续时间的这4个维度来解释一下这几种记忆:1...
- Spring Boot整合MyBatis全面指南:从基础到高级应用(全网最全)
-
一、基础概念与配置1.1SpringBoot与MyBatis简介技术描述优点SpringBoot简化Spring应用开发的框架,提供自动配置、快速启动等特性快速开发、内嵌服务器、自动配置、无需X...
- 5大主流方案对比:MySQL千亿级数据线上平滑扩容实战
-
一、扩容方案剖析1、扩容问题在项目初期,我们部署了三个数据库A、B、C,此时数据库的规模可以满足我们的业务需求。为了将数据做到平均分配,我们在Service服务层使用uid%3进行取模分片,从而将数据...
- PostgreSQL 技术内幕(五)Greenplum-Interconnect模块
-
Greenplum是在开源PostgreSQL的基础上,采用MPP架构的关系型分布式数据库。Greenplum被业界认为是最快最具性价比的数据库,具有强大的大规模数据分析任务处理能力。Greenplu...
- 在实际操作过程中如何避免出现SQL注入漏洞
-
一前言本文将针对开发过程中依旧经常出现的SQL编码缺陷,讲解其背后原理及形成原因。并以几个常见漏洞存在形式,提醒技术同学注意相关问题。最后会根据原理,提供解决或缓解方案。二SQL注入漏洞的原理、形...
- 运维从头到尾安装日志服务器,看这一篇就够了
-
一、rsyslog部署1.1)rsyslog介绍Linux的日志记录了用户在系统上一切操作,看日志去分析系统的状态是运维人员必须掌握的基本功。rsyslog日志服务器的优势:1、日志统一,集中式管理...
- 一周热门
-
-
Python实现人事自动打卡,再也不会被批评
-
Psutil + Flask + Pyecharts + Bootstrap 开发动态可视化系统监控
-
【验证码逆向专栏】vaptcha 手势验证码逆向分析
-
一个解决支持HTML/CSS/JS网页转PDF(高质量)的终极解决方案
-
再见Swagger UI 国人开源了一款超好用的 API 文档生成框架,真香
-
网页转成pdf文件的经验分享 网页转成pdf文件的经验分享怎么弄
-
C++ std::vector 简介
-
系统C盘清理:微信PC端文件清理,扩大C盘可用空间步骤
-
10款高性能NAS丨双十一必看,轻松搞定虚拟机、Docker、软路由
-
python使用fitz模块提取pdf中的图片
-
- 最近发表
-
- MySQL合集-mysql5.7及mysql8的一些特性
- MySQL 双表架构在房产中介房源管理中的深度实践
- MySQL 5.7 JSON 数据类型使用总结
- MySQL 8.0 SQL优化黑科技,面试官都不一定知道!
- 如何在 MySQL 中使用 JSON 数据(mysql的json函数与实例)
- MySQL中JSON的存储原理(mysql中json字段操作)
- mysql 之json字段详解(多层复杂检索)
- VMware vCenter Server 8.0U3b 发布下载,新增功能概览
- Spring Boot 3.x 新特性详解:从基础到高级实战
- 如何设计Agent的记忆系统(agent记忆方法)
- 标签列表
-
- 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)
- table.render (33)
- uniapp textarea (33)
- python判断元素在不在列表里 (34)
- python 字典删除元素 (34)
- vscode切换git分支 (35)
- python bytes转16进制 (35)
- grep前后几行 (34)
- hashmap转list (35)