You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Selenium Java测试中自动化Microsoft移动端MFA认证?

解决Microsoft Authenticator MFA自动化问题(Java + Selenium)

先排查当前TOTP验证码无效的问题

你用de.taimos的TOTP库生成的验证码无效,大概率是以下原因,逐一排查:

  1. 密钥格式错误
    Microsoft Authenticator的TOTP密钥是纯Base32字符串,不含空格、换行或其他符号。确认你获取的密钥是从账户安全设置导出的原始密钥(不是二维码解析后的额外参数),如果密钥里有空格,要全部移除。
  2. 时间同步问题
    TOTP依赖客户端与服务器时间严格同步(误差不能超过30秒)。检查测试机器的系统时间是否开启自动同步,确保和UTC时间一致。
  3. TOTP参数不匹配
    Microsoft的TOTP默认使用SHA1哈希算法、30秒时间步长、6位验证码。你可以显式指定参数确保匹配:
    public static String getTOTPCode(String secretKey) {
        Base32 base32 = new Base32();
        // 移除密钥中的所有空格
        byte[] bytes = base32.decode(secretKey.replaceAll("\\s+", ""));
        String hexKey = Hex.encodeHexString(bytes);
        // 显式指定Microsoft标准的TOTP参数
        return TOTP.getOTP(hexKey, System.currentTimeMillis(), "HmacSHA1", 30, 6);
    }
    

其他可行的自动化解决方案

如果TOTP方式始终无法生效,或者需要更稳定的方案,可尝试以下几种:

1. 使用资源所有者密码凭证流(ROPC Flow)

这是Azure AD支持的认证流,允许直接用用户名、密码加TOTP验证码获取访问令牌,跳过浏览器登录流程。需要Azure AD管理员为测试账号开启该流,仅建议在测试环境使用。
示例代码(基于MSAL for Java):

import com.microsoft.aad.msal4j.*;
import java.util.Collections;

public class MsalMfaAuth {
    public static void main(String[] args) throws Exception {
        String clientId = "你的测试应用Client ID";
        String tenantId = "你的Azure AD租户ID";
        String username = "测试账号用户名";
        String password = "测试账号密码";
        String totpCode = getTOTPCode("你的TOTP密钥");

        PublicClientApplication pca = PublicClientApplication.builder(clientId)
                .authority("https://login.microsoftonline.com/" + tenantId)
                .build();

        UserNamePasswordParameters parameters = UserNamePasswordParameters.builder(
                Collections.singleton("你的目标应用权限"),
                username,
                password.toCharArray())
                .build();
        // 传入TOTP验证码
        parameters.additionalParameters().put("code", totpCode);

        IAuthenticationResult result = pca.acquireToken(parameters).join();
        String accessToken = result.accessToken();
        // 可将accessToken注入浏览器Cookie,直接跳过登录流程
    }
}

2. 使用Appium控制Microsoft Authenticator应用

如果允许使用移动设备模拟器或真机,可通过Appium自动化打开Microsoft Authenticator,定位并读取验证码,再传入Selenium的登录页面:

  • 配置Appium环境,连接模拟器/真机
  • 编写Appium脚本启动应用,定位对应账号的验证码元素
  • 将读取到的验证码传入Selenium的输入框

3. 申请测试专用MFA配置

联系客户的Azure AD管理员,为测试账号设置:

  • 临时MFA豁免(仅测试时段生效)
  • 生成可重复使用的一次性MFA密码

内容的提问来源于stack exchange,提问作者jack.spar1122

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 10:40:16