【问题标题】:Authorization token generation for Azure Resource Management Rest APIAzure 资源管理 Rest API 的授权令牌生成
【发布时间】:2019-05-23 00:41:24
【问题描述】:

我将从我的 Spring Boot 应用程序调用 Azure Resource Management Rest API。为此,我需要有授权令牌。在谷歌搜索了不同的来源之后,我可以理解我们需要调用 POST API 来使用下面的 URL 生成授权令牌;

https://login.microsoftonline.com/{tenant_id}/oauth2/token

下面的请求正文,下面是我通过创建服务原则和活动目录得到的详细信息

client_secret 资源
授予类型
租户 ID

Spring boot java代码:

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    String url= "https://login.microsoftonline.com/{tenant_id}/oauth2/token";
    AuthTokenBody authTokenBody = service.setBody();
    headers.setContentType(MediaType.APPLICATION_JSON);
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    HttpEntity<AuthTokenBody> entity = new HttpEntity<>(authTokenBody, headers);
    ResponseEntity response= restTemplate.postForObject(url, entity, ResponseEntity.class);

但我得到以下错误:

{ "时间戳": "2018-12-23T11:52:58.175+0000", “状态”:500, "error": "内部服务器错误", "message": "400 错误请求", “路径”:“/cdaas/app” }

能否请您指导如何在 Spring-boot 中调用生成身份验证代码来校准 Azure 资源管理。

提前谢谢你

【问题讨论】:

标签: java azure spring-boot active-directory


【解决方案1】:

请参考下面的代码,它对我有用。

import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;
import com.microsoft.aad.adal4j.ClientCredential; // for service principal

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class GetAuthCode {
    public static void main(String[] args) {
        // Account specific values
        String tenantId = "***";
        String clientId = "***";
        String password = "***";

        // use adal to Authenticate
        AuthenticationContext authContext = null;
        AuthenticationResult authResult = null;
        ExecutorService service = null;

        try {
            service = Executors.newFixedThreadPool(1);
            String url = "https://login.microsoftonline.com/" + tenantId + "/oauth2/authorize";
            authContext = new AuthenticationContext(url,
                    false,
                    service);
            ClientCredential clientCred = new ClientCredential(clientId, password);
            Future<AuthenticationResult> future = authContext.acquireToken(
                    "https://management.azure.com/",
                    clientCred,
                    null);
            authResult = future.get();
            System.out.println(authResult.getAccessToken());
        } catch (Exception ex) {
            // handle exception as needed
        } finally {
            service.shutdown();
        }
    }
}

更多详情,请导航至doc。

【讨论】:

  • 刷新令牌怎么样?
  • 为什么 authResult.getRefreshToken() 为空?
猜你喜欢
  • 1970-01-01
  • 2021-10-20
  • 2019-07-16
  • 1970-01-01
  • 2016-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-10
相关资源
最近更新 更多