【问题标题】:How to get Client Secret Key Expiry date in java如何在java中获取客户端密钥到期日期
【发布时间】:2019-08-19 12:38:29
【问题描述】:

我在 Azure AD 租户中注册了应用程序,这些应用程序具有客户端 ID 和密码。 我需要获取 azure 应用程序凭据的到期日期。我在我的应用程序中使用 azure sdk for java。 我们如何使用 java 获取客户端密钥的到期日期?

我已经搜索过它,但没有找到任何有用的链接。谁能帮我解决这个问题。

【问题讨论】:

    标签: java azure azure-active-directory


    【解决方案1】:

    如果您想在您的 Java 应用程序中获取秘密到期日期,您可以拨打Microsoft Graph API 来获取该应用程序。然后应用程序的属性passwordCredentials 具有信息。例如

    使用 Azure 门户注册新应用程序

    1. 使用工作或学校帐户登录 Azure 门户,或者 个人 Microsoft 帐户。

    2. 如果您的帐户允许您访问多个租户,请在右上角选择您的帐户,并将您的门户会话设置为您想要的 Azure AD 租户。

    3. 在左侧导航窗格中,选择 Azure Active Directory 服务,然后选择应用注册 > 新注册。

    配置应用程序所需的 Microsoft Graph 权限

    代码

      //install ADAL4J get accesss token
        String clientId = "your application id";
        String appKey = "your client secret";
        String tenantId = "your tenant id";
        String authority =String.format("https://login.microsoftonline.com/",getTenantContextId())
        String resourceUrl = "https://graph.microsoft.com"
        ExecutorService service =  Executors.newFixedThreadPool(1);
        AuthenticationContext context = ew AuthenticationContext(authority, false, service); 
        ClientCredential clientCred = new ClientCredential(
                    clientId, appKey);
        Future<AuthenticationResult> future = context.acquireToken(resourceUrl, clientCred, null);
         AuthenticationResult result = future.get();
        
        //Call Microsoft graph api
       String stringUrl ="https://graph.microsoft.com/beta/applications?$filter=appId eq '{ApplicationId}'";
            URL url = new URL(stringUrl.replaceAll(" ","%20"));
    
             HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Authorization", "Bearer " + result.getAccessToken());
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Content-Type", "application/json");
    
            int httpResponseCode = conn.getResponseCode();
            if (httpResponseCode == 200 ) {
                BufferedReader in = null;
                 StringBuilder response;
    
                    in = new BufferedReader(
                            new InputStreamReader(conn.getInputStream()));
                    String inputLine;
                    response = new StringBuilder();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
    
                    in.close();
                JSONObject jb = new JSONObject(response.toString());
    
      
    

    更多详情请参考document

    更新

    请使用以下代码获取访问令牌

    String authority = "https://login.microsoftonline.com/" + tenant;
            ExecutorService service = Executors.newFixedThreadPool(1);
            AuthenticationContext context = new AuthenticationContext(authority, true, service);
            ClientCredential cred = new ClientCredential(clientId, clientSecret);
            String resourceId ="https://graph.microsoft.com";
            Future<AuthenticationResult> future = context.acquireToken(resourceId, cred, null);
            AuthenticationResult result = future.get();
            String accesstoken = result.getAccessToken();
    

    【讨论】:

    • 嗨 Jim,这里的 getTenantContextId() 方法是什么。我通过授予“login.microsoftonline.com/tenantIdValue/oauth2/authorize”权限来尝试这个示例。但我总是收到 401 响应代码,错误提示 java.io.IOException: Server returned HTTP response code: 401 for URL: URL.
    • 谢谢吉姆,我尝试了更新的答案。现在我得到的响应代码为 403。 java.io.IOException: Server returned HTTP response code: 403 for URL:URL.
    • @rupa 请检查您的 Azure AD 应用程序是否有足够的图形 API 权限。它应该具有“Application.ReadWrite.All”和“Directory.Read.All”权限。更多API详情请参考docs.microsoft.com/en-us/graph/api/…
    【解决方案2】:
    1. Add an auth file(可选但建议,您可以在代码中直接使用客户端ID和密码)

    2. Use Azure Management Libraries for Java

    <dependency>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>azure</artifactId>
        <version>1.24.2</version>
    </dependency>
    
    1. 代码示例
        public static void main(String[] args) throws IOException {
            File credFile = new File(ClassLoader.getSystemResource("./others/xh.auth").getPath());
    
            ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile);
            Azure.Authenticated authenticated = Azure.configure().authenticate(credentials);
    
            String appObjectId = "b48bc188-ff55-4655-a1d0-b8590c179a99";
    
            ActiveDirectoryApplication application = authenticated.activeDirectoryApplications().getById(appObjectId);
    
            Map<String, PasswordCredential> map = application.passwordCredentials();
    
            for ( Map.Entry<String,PasswordCredential> entry: map.entrySet()) {
                String key = entry.getKey();
                PasswordCredential value = entry.getValue();
                System.out.println("Name -> " + key + " ; End date -> " + value.endDate().toString());
            }
    
        }
    
    1. 输出
        Name -> t o m  ; End date -> 2299-12-30T16:00:00.000Z
        Name-> 3ba9bb7b-5251-4bbb-a373-658e346eb44d ; End date -> 2299-12-30T16:00:00.000Z
        Name-> p o s t m a n  ; End date -> 2299-12-30T16:00:00.000Z
    

    更新:

    您可以从门户获取应用程序对象ID:

    更新2:

    有一个getByName方法:

    ActiveDirectoryApplication byName = authenticated.activeDirectoryApplications().getByName("");
    

    但是有一个已知问题。因为在 Azure AD 中注册的应用程序可能具有相同的名称。这种方法不会得到正确的 如您所料,ActiveDirectoryApplication 实例。您将始终获得列表中的第一个。 (实际上,使用 REST API 和过滤器,您也会得到一个列表)

    但是,如果您已经创建了不同名称的所有应用程序,那么您可以使用 getByName 方法。

    【讨论】:

    • 感谢您的回答。这里的 appObjectId 是什么?是注册应用的objectId还是applicationId?我的应用程序中有 applicationId 和 secret,但我没有 objectId。
    • 是的,在我们拥有的门户中,但我如何使用 java 获取它。我无法对 objectId 值进行硬编码,因为这应该是动态的。
    • @Jack Jia 感谢您的更新,我们可以使用对象 ID 获取密码凭据。如果我们有多个密码凭据,如您在上面显示的输出,有没有办法获得特定的密码凭据结束日期。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 2016-01-17
    相关资源
    最近更新 更多