如何在Java+MSAL+Microsoft Graph API中获取设备代码流的URL与设备码
解决方案:提取设备代码流的登录URL和设备码
你不需要解析打印的文本内容,DeviceCodeChallenge对象本身就提供了直接获取登录URL和设备码的方法,直接调用属性即可完成提取,步骤如下:
- 在类中添加静态变量存储登录URL和设备码(如果是实例方法可改为实例变量):
public class DeviceCodeCredentialsTest { // 新增存储变量 private static String verificationUrl; private static String deviceCode; private static final List<String> graphApiScopes = Arrays.asList("https://graph.microsoft.com/.default"); // 原有构造方法和其他代码... }
- 修改
DeviceCodeCredentialBuilder的challengeConsumer逻辑,直接从DeviceCodeChallenge对象提取值:
final DeviceCodeCredential deviceCodeCred = new DeviceCodeCredentialBuilder() .clientId(Constants.CLIENT_ID) .tenantId(Constants.AUTH_TENANT) .challengeConsumer(challenge -> { // 直接提取登录URL和设备码到变量 verificationUrl = challenge.getVerificationUri(); deviceCode = challenge.getUserCode(); // 可选:保留打印用于调试 System.out.printf("To sign in, use a web browser to open the page %s and enter the code %s to authenticate.%n", verificationUrl, deviceCode); }) .build();
- 现在你可以在代码的任意位置使用
verificationUrl和deviceCode变量,比如结合Selenium自动打开浏览器并填充设备码:
// 示例Selenium代码(需引入Selenium依赖) WebDriver driver = new ChromeDriver(); driver.get(verificationUrl); // 定位输入框并填充设备码 WebElement codeInput = driver.findElement(By.id("code")); codeInput.sendKeys(deviceCode); // 定位提交按钮并点击 WebElement submitBtn = driver.findElement(By.id("submit")); submitBtn.click();
关键说明
challenge.getVerificationUri():返回设备登录的官方URL(如https://microsoft.com/devicelogin)challenge.getUserCode():返回需要用户输入的设备验证码(如ABCDEFGHI)
这种方式比解析字符串更可靠,避免了因消息格式变更导致的解析失败问题。
内容的提问来源于stack exchange,提问作者Nitin Rathod
相关产品推荐
相关产品推荐

