如何通过Spring Cloud Azure读取应用客户端密钥及过期时间
问题解答
com.azure.spring:spring-cloud-azure-starter-active-directory本身不直接支持读取Azure AD应用客户端密钥的过期时间,这个starter的核心定位是与Spring Security集成,实现OAuth2身份认证、权限管控等身份相关功能,并不包含读取应用密钥元数据的能力。如果你想基于Spring Cloud Azure生态实现需求,可以使用
com.azure.spring:spring-cloud-azure-starter-graph这个starter,它封装了Microsoft Graph SDK,能让你在Spring应用中更便捷地调用Graph API获取目标信息:添加依赖
在pom.xml中引入:<dependency> <groupId>com.azure.spring</groupId> <artifactId>spring-cloud-azure-starter-graph</artifactId> </dependency>配置认证信息
在application.yml中配置Azure AD的租户ID、客户端ID、客户端密钥(注意该应用需要拥有Application.Read.All或Application.ReadWrite.All的Graph API权限,且已获得管理员同意):spring: cloud: azure: active-directory: profile: tenant-id: <你的租户ID> credential: client-id: <你的应用客户端ID> client-secret: <你的应用客户端密钥>编写代码获取密钥过期时间
注入GraphServiceClient后,调用Graph API查询目标应用的passwordCredentials字段,该字段包含密钥的过期时间:import com.microsoft.graph.models.Application; import com.microsoft.graph.models.PasswordCredential; import com.microsoft.graph.service.GraphServiceClient; import org.springframework.stereotype.Component; @Component public class AppSecretService { private final GraphServiceClient graphClient; public AppSecretService(GraphServiceClient graphClient) { this.graphClient = graphClient; } public void getAppSecretExpiration(String appId) { Application application = graphClient.applications().byAppId(appId).get(); for (PasswordCredential credential : application.getPasswordCredentials()) { System.out.println("密钥ID: " + credential.getKeyId()); System.out.println("过期时间: " + credential.getExpirationDateTime()); } } }
关键注意点:必须为你的Azure AD应用注册添加对应的Graph API权限(
Application.Read.All或更高),并完成管理员同意,否则调用API时会出现权限不足的错误。
内容的提问来源于stack exchange,提问作者mdrg
相关产品推荐
相关产品推荐

