最新Spring Security实战教程(十七)企业级安全方案设计 - 多因素认证(MFA)实现

在这里插入图片描述

🌷 古之立大事者,不惟有超世之才,亦必有坚忍不拔之志
🎐 个人CSND主页——Micro麦可乐的博客
🐥《Docker实操教程》专栏以最新的Centos版本为基础进行Docker实操教程,入门到实战
🌺《RabbitMQ》专栏19年编写主要介绍使用JAVA开发RabbitMQ的系列教程,从基础知识到项目实战
🌸《设计模式》专栏以实际的生活场景为案例进行讲解,让大家对设计模式有一个更清晰的理解
🌛《开源项目》本专栏主要介绍目前热门的开源项目,带大家快速了解并轻松上手使用
✨《开发技巧》本专栏包含了各种系统的设计原理以及注意事项,并分享一些日常开发的功能小技巧
💕《Jenkins实战》专栏主要介绍Jenkins+Docker的实战教程,让你快速掌握项目CI/CD,是2024年最新的实战教程
🌞《Spring Boot》专栏主要介绍我们日常工作项目中经常应用到的功能以及技巧,代码样例完整
🌞《Spring Security》专栏中我们将逐步深入Spring Security的各个技术细节,带你从入门到精通,全面掌握这一安全技术
如果文章能够给大家带来一定的帮助!欢迎关注、评论互动~

最新Spring Security实战教程(十七)企业级安全方案设计 - 多因素认证(MFA)实现

  • 1. 前言
  • 2. 为什么需要多因素认证?
      • 传统认证的风险
      • MFA的核心优势
      • 常见多因素认证实现方案
  • 3. 多因素认证的核心原理
  • 4. 系统架构与流程设计
      • ❶ 用户注册/初始化
      • ❷ 第一步:用户名+密码登录
      • ❸ TOTP 验证
      • ❹ 完整流程图
  • 5. Spring Security整合MFA实现
      • 5.1 引入依赖
      • 5.2 用户实体
      • 5.3 用户 Mapper
      • 5.4 TOTP 工具类(Google Authenticator 兼容)
      • 5.5 Service 层:用户与 MFA 逻辑
      • 5.6 安全配置(SecurityConfig.java)
        • 5.6 .1 自定义异常 MfaRequiredException.java
        • 6.5.2 自定义 AuthenticationProvider
        • 5.6.3 自定义过滤器 MfaAuthenticationFilter.java
        • 5.6.4 自定义失败处理器 CustomAuthenticationFailureHandler.java
        • 5.6.5 安全配置 SecurityConfig.java
      • 5.7 控制器:登录、MFA 验证、注册与秘钥初始化
      • 5.8 前端页面示例(Thymeleaf)
  • 6. 总结与落地建议
      • 实际生产环境推荐:

回顾链接:
最新Spring Security实战教程(一)初识Spring Security安全框架
最新Spring Security实战教程(二)表单登录定制到处理逻辑的深度改造
最新Spring Security实战教程(三)Spring Security 的底层原理解析
最新Spring Security实战教程(四)基于内存的用户认证
最新Spring Security实战教程(五)基于数据库的动态用户认证传统RBAC角色模型实战开发
最新Spring Security实战教程(六)最新Spring Security实战教程(六)基于数据库的ABAC属性权限模型实战开发
最新Spring Security实战教程(七)方法级安全控制@PreAuthorize注解的灵活运用
最新Spring Security实战教程(八)Remember-Me实现原理 - 持久化令牌与安全存储方案
最新Spring Security实战教程(九)前后端分离认证实战 - JWT+SpringSecurity无缝整合
最新Spring Security实战教程(十)权限表达式进阶 - 在SpEL在安全控制中的高阶魔法
最新Spring Security实战教程(十一)CSRF攻防实战 - 从原理到防护的最佳实践
最新Spring Security实战教程(十二)CORS安全配置 - 跨域请求的安全边界设定
最新Spring Security实战教程(十三)会话管理机制 - 并发控制与会话固定攻击防护
最新Spring Security实战教程(十四)OAuth2.0精讲 - 四种授权模式与资源服务器搭建
最新Spring Security实战教程(十五)快速集成 GitHub 与 Gitee 的社交登录
最新Spring Security实战教程(十六)微服务间安全通信 - JWT令牌传递与校验机制

1. 前言

在微服务与分布式架构日益普及的今天,传统的 单一凭证(用户名+密码) 已经难以满足企业对于身份验证的高安全性需求。多因素认证(Multi‐Factor Authentication,简称 MFA) 通过用户知道的东西(如密码)+ 用户拥有的东西(如动态验证码)或 用户自身的一部分(如指纹)三种因素的组合,大幅提升了系统防护能力。

在这里插入图片描述

比如我们常的 GitHub腾讯云等就开启了MFAGitHub 开启 MFA后可以使用 使用Authenticator 应用扫描,而腾讯云则需要短信验证码来进行校验。

本章节博主将带着大家深入解析MFA,并基于 Spring Security 6 ,结合 MySQL 与 MyBatis-Plus,带你从理论到实战,快速构建一套企业级的 MFA 认证方案。


2. 为什么需要多因素认证?

传统认证的风险

  • 密码脆弱性:大部分的数据泄露源于弱密码或重复密码
  • 撞库攻击:黑客利用泄露的密码库尝试登录其他系统
  • 钓鱼攻击:伪造登录页面窃取用户凭证

MFA的核心优势

多因素认证(MFA)通过多种不同类别的凭证 来共同完成身份验证,显著提升安全性:

  • Something you know(你知道的东西):用户名与密码、PIN 码等;
  • Something you have(你拥有的东西):手机收到的 OTP、应用令牌(Authenticator)等;
  • Something you are(你自身的一部分):生物特征(指纹、面部识别等)。

当密码被破解或泄露后,如果没有第二因素(如手机动态验证码),攻击者依然无法登录。

常见多因素认证实现方案

认证方式安全性用户体验实施成本
SMS验证码★★☆★★★★★☆
邮件验证★★☆★★☆★★☆
TOTP★★★★★★☆★★★
生物识别★★★☆★★★★★★★★

本方案选择TOTP:平衡安全性与实施成本,兼容Google Authenticator等标准应用


3. 多因素认证的核心原理

TOTP(Time‐based One‐Time Password)为例:

  1. 服务端生成用户专属密钥(Secret Key),并在用户首次登录或在安全设置中心将其展示给用户(通常通过二维码形式扫描到 Google AuthenticatorAuthy 等应用中)
  2. 手机端应用(如 Google Authenticator)基于 Secret Key 与当前时间戳,通过 HMAC‐SHA1 算法计算出 6 位动态验证码
  3. 用户登录时,输入用户名+密码(第 1 因素),若校验通过,跳转到 MFA 验证页面,要求输入手机上展示的 6 位动态验证码(第 2 因素)
  4. 服务端验证客户端提交的动态验证码是否与基于相同 Secret Key 和当前时间戳计算出的值一致。若一致,则认为通过 MFA ,登录成功;否则,拒绝登录或提示重试

整个流程中,只有用户掌握 Secret Key(存在手机应用中),且需实时生成动态验证码,即使攻击者获得了用户名+密码,没有手机和 Secret Key,也无法通过第二因素验证。


4. 系统架构与流程设计

本章节以单体 Spring Boot 应用演示 MFA 流程,生产环境可拆分成独立的认证服务(Auth Service)与业务服务(Resource Service),二者均依赖集中管理的用户与 MFA 数据库。关键流程:

❶ 用户注册/初始化

后台管理员或用户注册时,系统为用户生成一对 RSA 密钥(可选)或仅生成 TOTP Secret,保存用户表中。

将生成的 Secret 以二维码或明文形式呈现给用户,用户通过 Google Authenticator 等扫描或手动录入。

❷ 第一步:用户名+密码登录

用户提交用户名+密码,Service 层校验密码(结合 BCrypt)。

校验成功后,将用户标记为“已通过第一步认证”,并生成一个短期令牌(可存放到 session 或 JWT)表示“待 MFA”状态,重定向到 MFA 验证页。

❸ TOTP 验证

用户在 MFA 验证页中输入 6 位动态验证码,提交后,后台从数据库中取出该用户的 Secret,通过 TOTP 算法生成当前时刻的合法验证码,进行比对。

若校验通过,则完成整个登录流程,Spring Security 将真正的 Authentication 对象置入 SecurityContext 中,登录成功,跳转到首页;否则,提示错误并重试。

❹ 完整流程图

在这里插入图片描述


5. Spring Security整合MFA实现

根据前面的章节我们已经整合好了 mysql + mybatis等的项目案例,我们继续追加子模块,引入Google Authenticator 兼容 TOTP 实现:com.warrenstrange:googleauth:1.5.0

5.1 引入依赖

下面以 pom.xml 为例,列出主要依赖:

<!-- pom.xml --><dependencies><!-- Spring Boot Starter Web + Thymeleaf --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><!-- Spring Security 6 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><!-- MyBatis-Plus & MySQL 驱动 --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.5</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!-- Google Authenticator TOTP 实现 --><dependency><groupId>com.warrenstrange</groupId><artifactId>googleauth</artifactId><version>1.5.0</version></dependency><!-- Lombok(可选) --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope></dependency><!-- 测试 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>

5.2 用户实体

@Data
@TableName("users")
public class User {@TableId(type = IdType.AUTO)private Long id;private String username;private String password;private Boolean enabled;private Boolean mfaEnabled;private String mfaSecret;private LocalDateTime createdAt;private LocalDateTime updatedAt;
}

使用 Lombok @Data 简化 getter/setter
mfaEnabled 与 mfaSecret 字段分别表示该用户是否启用 MFA 及其对应的 TOTP 密钥

5.3 用户 Mapper

@Mapper
public interface UserMapper extends BaseMapper<User> {// 如果需要自定义 SQL,可在此处声明
}

5.4 TOTP 工具类(Google Authenticator 兼容)

我们将使用 com.warrenstrange.googleauth.GoogleAuthenticator 来生成并验证动态验证码(TOTP)

public class TotpUtils {private static final GoogleAuthenticator gAuth = new GoogleAuthenticator();/*** 为用户生成一个新的 TOTP 密钥(Base32 编码格式)** @return Base32 编码的密钥*/public static String generateSecretKey() {GoogleAuthenticatorKey key = gAuth.createCredentials();return key.getKey();}/*** 验证用户提交的 TOTP 码是否合法(基于用户的 Secret Key)** @param secretKey Base32 编码的 TOTP 密钥* @param code      用户提交的 6 位验证码* @return true 如果校验通过;false 否则*/public static boolean verifyTotp(String secretKey, int code) {return gAuth.authorize(secretKey, code);}/*** 将 Base32 编码的密钥转换为 Hex,若业务需要展示给前端 URI 可用该方法*/public static String getHexKey(String base32Secret) {Base32 codec = new Base32();byte[] bytes = codec.decode(base32Secret);return Hex.encodeHexString(bytes);}/*** 生成在 Google Authenticator 中添加账户的二维码 URI** @param username 用户名* @param secret   Base32 编码密钥* @param issuer   应用或企业名称,比如 "MyCompany"* @return otpauth://totp/issuer:username?secret=SECRET&issuer=issuer*/public static String getOtpAuthURL(String username, String secret, String issuer) {return String.format("otpauth://totp/%s:%s?secret=%s&issuer=%s",issuer, username, secret, issuer);}
}

说明

  • generateSecretKey():生成一个新的 Base32 格式秘钥,用于 TOTP 绑定。
  • verifyTotp(secretKey, code):校验用户提交的 6 位 TOTP 码是否与当前时刻计算值匹配。
  • getOtpAuthURL(...):方便在前端生成二维码,让用户用 Google Authenticator 扫描。

5.5 Service 层:用户与 MFA 逻辑

我们封装用户管理与 MFA 相关的业务逻辑到 UserService

IUserService.java(接口)

public interface IUserService {User findByUsername(String username);void register(User user);void enableMfa(Long userId);boolean verifyTotp(Long userId, int code);
}

UserServiceImpl.java(实现)

@Service
public class UserServiceImpl implements IUserService {@Autowiredprivate UserMapper userMapper;private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();@Overridepublic User findByUsername(String username) {return userMapper.selectOne(new QueryWrapper<User>().eq("username", username));}@Overridepublic void register(User user) {// 加密密码user.setPassword(passwordEncoder.encode(user.getPassword()));user.setEnabled(true);user.setMfaEnabled(false);user.setMfaSecret(null);userMapper.insert(user);}@Overridepublic void enableMfa(Long userId) {// 为用户生成 TOTP Secret 并更新User u = userMapper.selectById(userId);String secret = TotpUtils.generateSecretKey();u.setMfaSecret(secret);u.setMfaEnabled(true);userMapper.updateById(u);}@Overridepublic boolean verifyTotp(Long userId, int code) {User u = userMapper.selectById(userId);if (u == null || !u.getMfaEnabled() || u.getMfaSecret() == null) {return false;}return TotpUtils.verifyTotp(u.getMfaSecret(), code);}
}

说明

  • register(User):用户注册时将密码加密存库,初始不启用 MFA。
  • enableMfa(Long):为指定用户生成 TOTP Secret,更新到数据库,并将 mfaEnabled 标记为 true
  • verifyTotp(Long, int):验证用户提交的 TOTP 码是否正确。

5.6 安全配置(SecurityConfig.java)

Spring Security 6 中,我们需要覆盖默认的认证流程,实现分为两步的 MFA 登录。思路如下:

  1. 自定义 AuthenticationProvider:首先校验用户名+密码,如果用户启用了 MFA,就抛出一个自定义异常(MfaRequiredException),在 AuthenticationFailureHandler 中捕获并重定向到 MFA 验证页。
  2. 在 MFA 验证页中,用户提交 TOTP 码后,我们自定义一个 MfaAuthenticationFilter,从 session 中读取“待 MFA”状态的用户信息,再调用 Service 校验 TOTP。如果通过,则直接构建最终的 UsernamePasswordAuthenticationToken 并置入 SecurityContext。
5.6 .1 自定义异常 MfaRequiredException.java
public class MfaRequiredException extends AuthenticationException {private final String username;public MfaRequiredException(String msg, String username) {super(msg);this.username = username;}public String getUsername() {return username;}
}
6.5.2 自定义 AuthenticationProvider
/*** 第一步:校验用户名 + 密码* 如果用户启用 MFA,则抛出 MfaRequiredException,后续由 MfaAuthenticationFilter 处理*/
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {@Autowiredprivate IUserService userService;private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {String username = authentication.getName();String password = (String) authentication.getCredentials();User user = userService.findByUsername(username);if (user == null || !user.getEnabled()) {throw new BadCredentialsException("用户名或密码错误");}if (!passwordEncoder.matches(password, user.getPassword())) {throw new BadCredentialsException("用户名或密码错误");}// 如果用户启用了 MFA,则抛出自定义异常,提示进行第二步验证if (Boolean.TRUE.equals(user.getMfaEnabled())) {throw new MfaRequiredException("MFA 验证必需", username);}// 未启用 MFA 或继承走这里,直接构建 Authenticationreturn new UsernamePasswordAuthenticationToken(username, null,Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));}@Overridepublic boolean supports(Class<?> authentication) {return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);}
}

说明

  • 如果用户开启 mfaEnabled,校验密码后不直接登录,而是通过抛出异常告知后续过滤器进行 MFA 验证。
5.6.3 自定义过滤器 MfaAuthenticationFilter.java
/*** 该过滤器负责处理 /mfa-verify POST 请求,* 从 session 中获取待验证用户名,校验用户提交的 TOTP 码。*/
@Component
public class MfaAuthenticationFilter extends AbstractAuthenticationProcessingFilter {private final IUserService userService;public MfaAuthenticationFilter(IUserService userService) {super(new AntPathRequestMatcher("/mfa-verify", "POST"));this.userService = userService;// 不让 Spring Security 为我们阻止 CSRF,示例中 CSRF 已关闭}@Overridepublic org.springframework.security.core.Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {// 应用前端将用户名暂存到 sessionAttribute: "MFA_USER"String username = (String) request.getSession().getAttribute("MFA_USER");if (username == null) {throw new RuntimeException("会话中找不到待 MFA 用户");}// 获取用户提交的 TOTP 码String codeStr = request.getParameter("code");if (codeStr == null || codeStr.isEmpty()) {throw new RuntimeException("TOTP 码不能为空");}int code;try {code = Integer.parseInt(codeStr);} catch (NumberFormatException e) {throw new RuntimeException("TOTP 码格式不正确");}// 从数据库校验 TOTPUser user = userService.findByUsername(username);boolean valid = userService.verifyTotp(user.getId(), code);if (!valid) {throw new RuntimeException("TOTP 验证失败");}// 验证成功,构建真正的 Authentication 对象UsernamePasswordAuthenticationToken auth =new UsernamePasswordAuthenticationToken(username, null, Collections.singletonList(() -> "ROLE_USER"));return auth;}@Overrideprotected void successfulAuthentication(HttpServletRequest request,HttpServletResponse response,FilterChain chain,org.springframework.security.core.Authentication authResult) throws IOException, ServletException {// 将最终的 Authentication 填入 SecurityContextSecurityContextHolder.getContext().setAuthentication(authResult);// 登录成功后清除 session 中的 MFA 用户标志request.getSession().removeAttribute("MFA_USER");// 跳转到首页response.sendRedirect("/");}@Overrideprotected void unsuccessfulAuthentication(HttpServletRequest request,HttpServletResponse response,org.springframework.security.core.AuthenticationException failed) throws IOException, ServletException {// 验证失败,跳回 MFA 验证页面response.setContentType(MediaType.TEXT_PLAIN_VALUE);response.getWriter().write("MFA 验证失败:" + failed.getMessage());response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);}
}

说明

  • 该过滤器拦截 POST /mfa-verify 请求,读取 session 中预先放置的 “MFA_USER” 用户名,以及前端提交的 code
  • 调用 userService.verifyTotp(...) 校验动态验证码,若通过则构建最终的 Authentication
5.6.4 自定义失败处理器 CustomAuthenticationFailureHandler.java
/*** 处理第一步用户名/密码登录失败或触发 MFA 的情况*/
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {@Overridepublic void onAuthenticationFailure(HttpServletRequest request,HttpServletResponse response,AuthenticationException exception) throws IOException, ServletException {// 如果是 MfaRequiredException,重定向到 /mfa 页面,并将用户名存入 sessionif (exception instanceof MfaRequiredException) {String username = ((MfaRequiredException) exception).getUsername();request.getSession().setAttribute("MFA_USER", username);// 重定向到 MFA 验证页面response.sendRedirect("/mfa");} else {// 普通登录失败,重定向回 /login?errorresponse.sendRedirect("/login?error=true");}}
}

说明

  • CustomAuthenticationProvider 抛出 MfaRequiredException 时,说明用户通过密码校验但需要第二步 MFA,此时将“待 MFA”用户名写入 session,并重定向到 MFA 验证页面 /mfa
  • 普通失败(如密码错误)则带上 ?error=true 重定向回登录页。
5.6.5 安全配置 SecurityConfig.java
/*** 核心安全配置:*  1. 注入自定义 AuthenticationProvider*  2. 配置表单登录和 MfaAuthenticationFilter*/
@Configuration
public class SecurityConfig {@Autowiredprivate CustomAuthenticationProvider customAuthenticationProvider;@Autowiredprivate MfaAuthenticationFilter mfaAuthenticationFilter;@Autowiredprivate CustomAuthenticationFailureHandler customFailureHandler;@Beanpublic SecurityFilterChain filterChain(HttpSecurity http, AuthenticationConfiguration authConfig) throws Exception {// 禁用 CSRF 简化示例http.csrf(csrf -> csrf.disable());// 使用自定义 AuthenticationProvider 替换默认的 DaoAuthenticationProviderhttp.authenticationProvider(customAuthenticationProvider);// 1. 首先,配置表单登录http.authorizeHttpRequests(auth -> auth.requestMatchers("/login", "/register", "/css/**", "/js/**").permitAll().anyRequest().authenticated()).formLogin(form -> form.loginPage("/login").loginProcessingUrl("/login") // 与表单提交 action 保持一致.failureHandler(customFailureHandler).defaultSuccessUrl("/", true));// 2. 注册 MFA 过滤器,它要在 UsernamePasswordAuthenticationFilter 之后执行http.addFilterAfter(mfaAuthenticationFilter, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.class);// 3. Session 管理:MFA 过程中会话保持http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED));// 4. 未授权时返回 401http.exceptionHandling(ex -> ex.authenticationEntryPoint((request, response, authException) ->response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized")));return http.build();}// 若需手动获取 AuthenticationManager,可使用以下 Bean@Beanpublic AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {return authConfig.getAuthenticationManager();}
}

关键点

  1. CustomAuthenticationProvider 注册到 Spring Security,替代默认的用户名/密码校验逻辑。
  2. 配置表单登录,登录失败由 CustomAuthenticationFailureHandler 处理。
  3. 注册 MfaAuthenticationFilter,拦截 /mfa-verify 提交。
  4. SessionPersist 保持“待 MFA”状态直到第二步完成。

5.7 控制器:登录、MFA 验证、注册与秘钥初始化

我们需要提供几个页面和对应的 Controller:

  • /login:自定义登录页面(用户名+密码)
  • /register:用户注册页面
  • /mfa:MFA 验证页面,用户输入 6 位 TOTP 码
  • /mfa-verify:MFA 验证提交接口,由 MfaAuthenticationFilter 处理
  • /enable-mfa:在用户登录后打开此接口可为用户生成 TOTP Secret,并展示二维码
@Controller
public class AuthController {@Autowiredprivate IUserService userService;/*** 登录页(第一步:用户名 + 密码)*/@GetMapping("/login")public String loginPage(@RequestParam(required = false) String error, Model model) {model.addAttribute("error", error != null);return "login";}/*** 注册页(仅示例)*/@GetMapping("/register")public String registerPage() {return "register";}@PostMapping("/register")public String doRegister(@RequestParam String username, @RequestParam String password) {User u = new User();u.setUsername(username);u.setPassword(password);userService.register(u);return "redirect:/login";}/*** MFA 验证页:用户输入动态验证码*/@GetMapping("/mfa")public String mfaPage(HttpSession session, Model model) {String username = (String) session.getAttribute("MFA_USER");if (username == null) {// 无待验证用户,跳到登录页return "redirect:/login";}model.addAttribute("username", username);return "mfa";}/*** 启用 MFA:登录后用户请求此接口可获取 TOTP Secret 与二维码 URL*/@GetMapping("/enable-mfa")public String enableMfa(Authentication authentication, Model model) {if (authentication == null || !authentication.isAuthenticated()) {return "redirect:/login";}String username = authentication.getName();User u = userService.findByUsername(username);if (u.getMfaEnabled()) {model.addAttribute("message", "MFA 已启用");return "home";}// 为用户生成秘钥并开启 MFAuserService.enableMfa(u.getId());u = userService.findByUsername(username); // 刷新String secret = u.getMfaSecret();String otpAuthURL = TotpUtils.getOtpAuthURL(username, secret, "MyCompany");model.addAttribute("otpAuthURL", otpAuthURL);model.addAttribute("secret", secret);return "enable-mfa";}@GetMapping("/")public String homePage() {return "home";}
}

说明

  • GET /enable-mfa 用于用户主动绑定 MFA(生成 Secret 并呈现给用户)。若业务要求后台自动开通,可在注册后直接调用 userService.enableMfa(...)

5.8 前端页面示例(Thymeleaf)

为简化,以下示例仅为最基本表单。生产环境可加入更丰富的样式与 JS 验证。

login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>登录</title>
</head>
<body>
<h2>登录</h2>
<form th:action="@{/login}" method="post"><div><label>用户名:</label><input type="text" name="username" required/></div><div><label>密码:</label><input type="password" name="password" required/></div><div th:if="${error}"><p style="color:red;">用户名或密码错误</p></div><div><button type="submit">登录</button></div>
</form>
<p>没有账号?<a th:href="@{/register}">注册</a></p>
</body>
</html>

register.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>注册</title>
</head>
<body>
<h2>注册</h2>
<form th:action="@{/register}" method="post"><div><label>用户名:</label><input type="text" name="username" required/></div><div><label>密码:</label><input type="password" name="password" required/></div><div><button type="submit">注册</button></div>
</form>
<p>已有账号?<a th:href="@{/login}">登录</a></p>
</body>
</html>

mfa.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>MFA 验证</title>
</head>
<body>
<h2>多因素认证</h2>
<p>用户 <span th:text="${username}"></span>,请输入手机应用上的 6 位动态验证码:</p>
<form th:action="@{/mfa-verify}" method="post"><div><label>动态验证码:</label><input type="text" name="code" pattern="\\d{6}" maxlength="6" required/></div><div><button type="submit">验证</button></div>
</form>
</body>
</html>

enable-mfa.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>启用 MFA</title>
</head>
<body>
<h2>启用多因素认证 (MFA)</h2>
<p>请使用 Google Authenticator 或其他兼容 TOTP 的应用扫描下方二维码,或使用秘钥手动添加:</p>
<div><!-- 可以使用前端库生成二维码,此处直接展示 URI,方便生成 QR --><p>OTPAuth URL: <span th:text="${otpAuthURL}"></span></p><p>Secret Key: <span th:text="${secret}"></span></p>
</div>
<p>设置完成后,请退出重新登录并输入动态验证码。</p>
</body>
</html>

home.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>首页</title>
</head>
<body>
<h2>欢迎来到系统</h2>
<p>您已成功登录(且通过 MFA 验证)。</p>
<p><a th:href="@{/enable-mfa}">启用 MFA(如果尚未启用)</a></p>
<form th:action="@{/logout}" method="post"><button type="submit">退出登录</button>
</form>
</body>
</html>

注意

  • 如果需要在页面中展示二维码,可以使用前端 QRCode.js 等库,将 otpAuthURL 渲染为二维码。

6. 总结与落地建议

本文从“为什么需要多因素认证”入手,讲解了基于 TOTP 的 MFA 核心原理,并详细演示了如何在 Spring Security 6 中分两步完成登录与 MFA 验证的流程。关键点回顾:

  1. 第一步:用户名+密码

    • 自定义 AuthenticationProvider,校验用户名与密码;
    • 若用户启用 MFA,则抛出 MfaRequiredException,并将用户名暂存到 Session。
  2. 第二步:TOTP 验证

    • 自定义 MfaAuthenticationFilter,拦截 /mfa-verify 请求;
    • 从 Session 中获取“待 MFA”用户名,调用服务端 TOTP 校验逻辑;
    • 校验通过后,构建最终 Authentication 并置入 SecurityContext
  3. MySQL + MyBatis-Plus

    • 在数据库 users 表中增加 mfa_enabledmfa_secret 字段;
    • Service 层通过 Google Authenticator 兼容库生成并验证动态验证码;
    • MyBatis-Plus 简化了实体与 Mapper 的开发。

实际生产环境推荐:

  • 二维码展示与绑定:在 /enable-mfa 页面使用前端二维码生成库(如 qrcode.js)将 otpAuthURL 渲染为二维码图片,方便用户扫码。
  • 密钥保护mfa_secret 为敏感数据,建议对其进行数据库加密存储或使用 KMS 等专用系统保护。
  • 备份码与恢复:当用户手机丢失时,可预先生成一组一次性“恢复码”,用户在绑定 MFA 时妥善保存,避免无法登录。
  • 登陆失败锁定:对于连续多次 TOTP 验证失败的账户,可暂时锁定或触发告警,防止暴力破解。
  • SSL/TLS 强制:确保所有页面(尤其是登录与 MFA 页面)使用 HTTPS,防止中间人攻击截获验证码。
  • 会话超时与防并发:可考虑对“待 MFA”状态的会话设置合理的超时时间(如 2 分钟),超时后必须重新进行第一步登录。

通过上面的设计与实现,企业级应用即可在原有用户名+密码的基础上,平滑地接入基于 TOTP 的多因素认证,大幅提升系统安全性,抵御常见的账户破解与钓鱼风险。

如果你在实践过程中有任何疑问或更好的扩展思路,欢迎在评论区留言,最后希望大家 一键三连 给博主一点点鼓励!


在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pswp.cn/web/82824.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

logstash拉取redisStream的流数据,并存储ES

先说结论&#xff0c; window验证logstash截至2025-06-06 是没有原生支持的。 为啥考虑用redisStream呢&#xff1f;因为不想引入三方的kafka等组件&#xff0c; 让服务部署轻量化&#xff0c; 所以使用现有的redis来实现&#xff0c; 为啥不用list呢&#xff1f; 已经用strea…

IEC 61347-1:2015 灯控制装置安全通用要求详解

IEC 61347-1:2015 灯控制装置安全通用要求详解 IEC 61347-1:2015《灯控制装置 第1部分&#xff1a;一般要求和安全要求》是国际电工委员会&#xff08;IEC&#xff09;制定的关于灯控制装置安全性能的核心基础标准。它为各类用于启动和稳定工作电流的灯控制装置&#xff08;如…

26、跳表

在C标准库中&#xff0c;std::map 和 std::set 是使用红黑树作为底层数据结构的容器。 红黑树是一种自平衡二叉搜索树&#xff0c;能够保证插入、删除和查找操作的时间复杂度为O(log n)。 以下是一些使用红黑树的C标准库容器&#xff1a; std::map&#xff1a;一种关联容器&a…

LabVIEW音频测试分析

LabVIEW通过读取指定WAV 文件&#xff0c;实现对音频信号的播放、多维度测量分析功能&#xff0c;为音频设备研发、声学研究及质量检测提供专业工具支持。 主要功能 文件读取与播放&#xff1a;支持持续读取示例数据文件夹内的 WAV 文件&#xff0c;可实时播放音频以监听被测信…

JUC并发编程(二)Monitor/自旋/轻量级/锁膨胀/wait/notify/锁消除

目录 一 基础 1 概念 2 卖票问题 3 转账问题 二 锁机制与优化策略 0 Monitor 1 轻量级锁 2 锁膨胀 3 自旋 4 偏向锁 5 锁消除 6 wait /notify 7 sleep与wait的对比 8 join原理 一 基础 1 概念 临界区 一段代码块内如果存在对共享资源的多线程读写操作&#xf…

Doris 与 Elasticsearch:谁更适合你的数据分析需求?

一、Doris 和 Elasticsearch 的基本概念 &#xff08;一&#xff09;Doris 是什么&#xff1f; Doris 是一个用于数据分析的分布式 MPP&#xff08;大规模并行处理&#xff09;数据库。它主要用于存储和分析大量的结构化数据&#xff08;比如表格数据&#xff09;&#xff0c…

使用Virtual Serial Port Driver+com2tcp(tcp2com)进行两台电脑的串口通讯

使用Virtual Serial Port Drivercom2tcp或tcp2com进行两台电脑的串口通讯 问题说明解决方案方案三具体操作流程网上教程软件安装拓扑图准备工作com2tcp和tcp2com操作使用串口助手进行验证 方案三存在的问题数据错误通讯延时 问题说明 最近想进行串口通讯的一个测试&#xff0c…

transformer和 RNN以及他的几个变体区别 改进

Transformer、RNN 及其变体&#xff08;LSTM/GRU&#xff09;是深度学习中处理序列数据的核心模型&#xff0c;但它们的架构设计和应用场景有显著差异。以下从技术原理、优缺点和适用场景三个维度进行对比分析&#xff1a; 核心架构对比 模型核心机制并行计算能力长序列依赖处…

CSS6404L 在物联网设备中的应用优势:低功耗高可靠的存储革新与竞品对比

物联网设备对存储芯片的需求聚焦于低功耗、小尺寸、高可靠性与传输效率&#xff0c;Cascadeteq 的 CSS6404L 64Mb Quad-SPI Pseudo-SRAM 凭借差异化技术特性&#xff0c;在同类产品中展现显著优势。以下从核心特性及竞品对比两方面解析其应用价值。 一、CSS6404L 核心产品特性…

go语言map扩容

map是什么&#xff1f; ​在Go语言中&#xff0c;map是一种内置的无序key/value键值对的集合&#xff0c;可以根据key在O(1)的时间复杂度内取到value&#xff0c;有点类似于数组或者切片结构&#xff0c;可以把数组看作是一种特殊的map&#xff0c;数组的key为数组的下标&…

2025年SDK游戏盾实战深度解析:防御T级攻击与AI反作弊的终极方案

一、引言&#xff1a;游戏安全的“生死防线” 2025年&#xff0c;全球游戏行业因DDoS攻击日均损失3.2亿元&#xff0c;攻击峰值突破8Tbps&#xff0c;且70% 的攻击为混合型&#xff08;DDoSCC&#xff09;。传统高防IP因延迟高、成本贵、协议兼容性差&#xff0c;已无法满足实…

【Linux】LInux下第一个程序:进度条

前言&#xff1a; 在前面的文章中我们学习了LInux的基础指令 【Linux】初见&#xff0c;基础指令-CSDN博客【Linux】初见&#xff0c;基础指令&#xff08;续&#xff09;-CSDN博客 学习了vim编辑器【Linux】vim编辑器_linux vim insert-CSDN博客 学习了gcc/g【Linux】编译器gc…

Web前端基础

### 一、浏览器 火狐浏览器、谷歌浏览器(推荐)、IE浏览器 推荐谷歌浏览器原因&#xff1a; 1、简洁大方,打开速度快 2、开发者调试工具&#xff08;右键空白处->检查&#xff0c;打开调试模式&#xff09; ### 二、开发工具 核心IDE工具 1. Visual Studio Code (VS Code)‌…

C++调试(肆):WinDBG分析Dump文件汇总

目录 1.前言 2.WinDBG中常用的指令 3.分析异常时要关注的信息 4.心得 前言 本篇博客主要针如何使用WinDBG工具调试Dump文件的流程进行一个讲解&#xff0c;具体捕获的Dump文件也是前两节例子中生成的Dump文件。 WinDBG中常用的指令 关于WinDBG调试时常用的指令主要分为以下几种…

SOC-ESP32S3部分:33-声学前端模型ESP-SR

飞书文档https://x509p6c8to.feishu.cn/wiki/YnbmwtqI5iBwE3kHA7AcZ3yTnLf ESP-SR 是乐鑫官方开发的一个音频组件&#xff0c;支持以下模块&#xff1a; 声学前端算法 AFE唤醒词检测 WakeNet命令词识别 MultiNet语音合成&#xff08;目前只支持中文&#xff09; 组件地址&am…

基于vscode,idea,java,html,css,vue,echart,maven,springboot,mysql数据库,在线考试系统

详细视频&#xff1a;【基于vscode,idea,java,html,css,vue,echart,maven,springboot,mysql数据库&#xff0c;在线考试系统-哔哩哔哩】 https://b23.tv/7hwmwmQ

【Linux】shell中的运行流程控制

目录 一.什么是运行流程控制 二.条件允许流程控制--if 2.1.单分支 2.2.双分支 2.3.多分支 if多分支练习 三.循环运行流程控制 无判定循环--for 判断循环--while&#xff0c;until 四.选择运行流程控制 五.自动应答--expect 5.1.固定位置的交互应答 5.2.非固定位置的…

新能源汽车热管理核心技术解析:冬季续航提升40%的行业方案

新能源汽车热管理核心技术解析&#xff1a;冬季续航提升40%的行业方案 摘要&#xff1a;突破续航焦虑的关键在热能循环&#xff01; &#x1f449; 本文耗时72小时梳理行业前沿方案&#xff0c;含特斯拉/比亚迪等8家车企热管理系统原理图 一、热管理为何成新能源车决胜关键&am…

OCR MLLM Evaluation

为什么需要评测体系&#xff1f;——背景与矛盾 ​​ 能干的事&#xff1a;​​ 看清楚发票、身份证上的字&#xff08;准确率>90%&#xff09;&#xff0c;速度飞快&#xff08;眨眼间完成&#xff09;。​​干不了的事&#xff1a;​​ 碰到复杂表格&#xff08;合并单元…

深入解析JVM工作原理:从字节码到机器指令的全过程

一、JVM概述 Java虚拟机(JVM)是Java平台的核心组件&#xff0c;它实现了Java"一次编写&#xff0c;到处运行"的理念。JVM是一个抽象的计算机器&#xff0c;它有自己的指令集和运行时内存管理机制。 JVM的主要职责&#xff1a; 加载&#xff1a;读取.class文件并验…