You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取azure-identity授权码凭证对应令牌并存储到Spring Boot会话中

实现步骤

你可以按照以下流程获取令牌并存储到会话中,不需要额外手动处理后续的令牌刷新逻辑:

1. 准备基础配置参数

提前在application.yml中配置好Azure AD应用注册的核心参数,避免硬编码:

  • 客户端ID(clientId)
  • 客户端密钥(clientSecret)
  • 租户ID(tenantId)
  • 授权回调重定向URI(redirectUri)

2. 拿到授权码后构建凭证并请求令牌

收到Azure AD重定向返回的code参数后,先构建AuthorizationCodeCredential实例,再主动拉取令牌:

// 构建授权码凭证
AuthorizationCodeCredential credential = new AuthorizationCodeCredentialBuilder()
    .clientId(clientId)
    .clientSecret(clientSecret)
    .tenantId(tenantId)
    .authorizationCode(code) // 填入回调拿到的授权码
    .redirectUri(redirectUri)
    .build();

// 配置Microsoft Graph的访问权限作用域
List<String> scopes = Arrays.asList("https://graph.microsoft.com/User.Read", "https://graph.microsoft.com/Mail.Read");
// 同步获取令牌响应,异步场景可直接处理返回的Mono对象
AccessToken token = credential.getToken(new TokenRequestContext().addScopes(scopes.toArray(new String[0]))).block();

3. 将内容存入服务端会话

你可以选择两种存储方案,根据业务需求二选一即可:

  • 方案1:仅存储令牌字段,适合需要自行管理令牌生命周期的场景
session.setAttribute("graph_access_token", token.getToken());
session.setAttribute("token_expire_timestamp", token.getExpiresAt().toEpochMilli());
  • 方案2:直接存储整个AuthorizationCodeCredential实例(更推荐)
    该实例内部已经封装了令牌缓存、自动刷新逻辑,后续调用Graph API不需要你手动处理刷新令牌,直接使用即可:
session.setAttribute("graph_credential", credential);

4. 后续调用Microsoft Graph API示例

如果使用了方案2存储凭证实例,后续直接构建Graph客户端发起请求即可:

AuthorizationCodeCredential credential = (AuthorizationCodeCredential) session.getAttribute("graph_credential");
GraphServiceClient graphClient = GraphServiceClient.builder()
    .authenticationProvider(new TokenCredentialAuthProvider(scopes, credential))
    .buildClient();
// 直接调用接口,内部会自动判断令牌是否过期、自动刷新
User currentUser = graphClient.me().buildRequest().get();

注意:不要将令牌存储到前端Cookie或本地存储中,仅保存在服务端会话内避免泄露风险。如果是分布式部署的应用,需要确保会话序列化配置支持AuthorizationCodeCredential对象的序列化,否则建议选择方案1自行管理令牌刷新。

内容的提问来源于stack exchange,提问作者Thomas Einwaller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 04:36:04