如何使用Azure SDK for Golang获取服务主体(SP)的过期日期?
使用Azure SDK for Go获取服务主体密钥过期日期
前提条件
- 已安装Azure SDK for Go相关依赖:
azidentity、msgraph-sdk-go - 服务主体需具备
Application.Read.All或更高权限的API权限(已完成管理员同意授予)
实现步骤及代码示例
package main import ( "context" "fmt" "log" "github.com/Azure/azure-sdk-go/sdk/azidentity" msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go" "github.com/microsoftgraph/msgraph-sdk-go/models" ) func main() { // 替换为你的租户ID、服务主体客户端ID、客户端密钥 tenantID := "your-tenant-id" clientID := "your-sp-client-id" clientSecret := "your-sp-client-secret" // 创建客户端密钥认证凭据 cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, clientSecret, nil) if err != nil { log.Fatalf("创建认证凭据失败: %v", err) } // 初始化Microsoft Graph客户端 graphClient, err := msgraphsdk.NewGraphServiceClientWithCredentials(cred, []string{"https://graph.microsoft.com/.default"}) if err != nil { log.Fatalf("初始化Graph客户端失败: %v", err) } // 根据客户端ID筛选目标服务主体,仅查询所需字段 filterStr := fmt.Sprintf("appId eq '%s'", clientID) requestParams := &msgraphsdk.ListApplicationsRequestBuilderGetQueryParameters{ Filter: &filterStr, Select: []string{"id", "passwordCredentials"}, } reqConfig := &msgraphsdk.ListApplicationsRequestBuilderGetRequestConfiguration{ QueryParameters: requestParams, } result, err := graphClient.Applications().Get(context.Background(), reqConfig) if err != nil { log.Fatalf("获取服务主体信息失败: %v", err) } // 遍历输出所有密钥的过期日期 if result.GetValue() != nil && len(result.GetValue()) > 0 { targetApp := result.GetValue()[0] if creds := targetApp.GetPasswordCredentials(); creds != nil { for _, cred := range creds { fmt.Printf("密钥ID: %s\n", *cred.GetKeyId()) fmt.Printf("过期日期: %v\n", *cred.GetEndDateTime()) fmt.Println("---") } } else { fmt.Println("该服务主体未配置密码凭据") } } else { fmt.Println("未找到匹配的服务主体") } }
关键说明
- 代码通过Microsoft Graph API查询服务主体的
passwordCredentials属性,其中endDateTime字段即为密钥的过期日期 - 若服务主体存在多个密钥,会遍历输出所有密钥的过期信息
- 运行前需确认服务主体已被授予Graph API的对应权限,否则会返回权限不足的错误
内容的提问来源于stack exchange,提问作者Amit Arora
相关产品推荐
相关产品推荐

