簡體   English   中英

是否可以將 DeviceCode 身份驗證流程與 Azure Java SDK 一起使用?

[英]Is it possible to use the DeviceCode authentication Flow with Azure Java SDK?

我使用 azure msal4j庫成功生成了IAuthenticationResult - 我看到了一個設備代碼,當將該代碼輸入瀏覽器時,它顯示了正確的范圍/權限,現在我想獲取此身份驗證結果並通過它進入 Azure-SDK 身份驗證,類似於:

    val result = DeviceCodeFlow.acquireTokenDeviceCode()


    val a: Azure = Azure.configure()
        .withLogLevel(LogLevel.BODY_AND_HEADERS)
        .authenticate(AzureCliCredentials.create(result))
        .withDefaultSubscription()

有誰知道在哪里看/或任何這樣做的樣本?

如果要使用msal4j庫獲取訪問令牌,則使用令牌管理 Azure 資源與 Azure 管理 SDK,請參考以下代碼

public class App {
    public static void main(String[] args) throws Exception {
        String subscriptionId = ""; // the subscription id
        String domain="";// Azure AD tenant domain 
        DeviceCodeTokenCredentials tokencred = new DeviceCodeTokenCredentials(AzureEnvironment.AZURE,domain);
         Azure azure =Azure.configure()
                           .withLogLevel(LogLevel.BASIC)
                           .authenticate(tokencred)
                           .withSubscription(subscriptionId);
                                  
         for(AppServicePlan plan : azure.appServices().appServicePlans().list()) {
                  
                  System.out.println(plan.name());
                  
                  }
    }  
}

// define a class to extend AzureTokenCredentials
 class DeviceCodeTokenCredentials extends AzureTokenCredentials{

    public DeviceCodeTokenCredentials(AzureEnvironment environment, String domain) {
        super(environment, domain);
    }

    @Override
    public String getToken(String resource) throws IOException {
        // use msal4j to get access token 
        String clientId="d8aa570a-68b3-4283-adbe-a1ad3c1dfd8d";// you Azure AD application app id
        String AUTHORITY = "https://login.microsoftonline.com/common/";
        Set<String> SCOPE = Collections.singleton("https://management.azure.com/user_impersonation");
        PublicClientApplication pca = PublicClientApplication.builder(clientId)
                .authority(AUTHORITY)
                .build();

        Consumer<DeviceCode> deviceCodeConsumer = (DeviceCode deviceCode) ->
        System.out.println(deviceCode.message());

      DeviceCodeFlowParameters parameters =
        DeviceCodeFlowParameters
                .builder(SCOPE, deviceCodeConsumer)
                .build();
      IAuthenticationResult result = pca.acquireToken(parameters).join();       
      return result.accessToken();
    } 
 }

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM