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

Keycloak配置Azure AD身份提供商后如何获取用户头像URL?

如何在Keycloak中从Azure AD获取用户头像URL

可以从Azure AD获取用户头像,但Azure AD的头像数据不在默认的ID Token或User Info响应中,需要通过Microsoft Graph API获取,或者使用Keycloak的脚本映射器实现。以下是具体配置方法:

方法一:使用Keycloak脚本映射器调用Microsoft Graph API获取头像

1. 配置Azure AD应用权限

  • 在Azure门户的应用注册中,找到你的Keycloak集成应用,进入API权限页面。
  • 添加Microsoft Graph的委派权限:User.Read(必须,用于读取用户基本信息)和User.ReadBasic.All(确保能访问头像资源)。
  • 点击授予管理员同意,完成权限激活。

2. 在Keycloak中添加脚本映射器

  • 进入Keycloak控制台,打开你的Azure AD身份提供商,切换到Mappers标签。
  • 点击Create,选择Script Mapper类型,配置如下:
    • Name: Azure Avatar Mapper
    • Script Type: JavaScript
    • Script:
      var accessToken = user.getFederationIdentity().getToken().getAccessToken();
      var graphUrl = "https://graph.microsoft.com/v1.0/me/photo/$value";
      
      var client = new org.apache.http.impl.client.CloseableHttpClient();
      var request = new org.apache.http.client.methods.HttpGet(graphUrl);
      request.setHeader("Authorization", "Bearer " + accessToken);
      
      try {
          var response = client.execute(request);
          if (response.getStatusLine().getStatusCode() == 200) {
              // 将头像二进制数据转为Base64,存储到Keycloak用户的picture属性
              var entity = response.getEntity();
              var bytes = org.apache.commons.io.IOUtils.toByteArray(entity.getContent());
              var base64Avatar = java.util.Base64.getEncoder().encodeToString(bytes);
              user.setSingleAttribute("picture", "data:image/jpeg;base64," + base64Avatar);
          }
      } catch (e) {
          // 处理请求失败的情况,比如用户没有头像时设置默认值
          user.setSingleAttribute("picture", "/path/to/default/avatar.png");
      } finally {
          client.close();
      }
      
    • 勾选Add to user session和Add to ID token(根据需求选择是否在Token中返回)。

方法二:通过Azure AD User Info端点尝试获取(仅部分场景可用)

部分Azure AD租户可能在User Info响应中返回picture声明,但这不是默认行为。可以尝试以下配置:

  • 在Keycloak的Azure AD身份提供商配置中,确保Scopes字段包含profile,然后添加一个Attribute Importer映射器:
    • Name: Azure Picture Importer
    • Attribute Name: picture
    • Claim JSON Path: $.picture
    • 如果User Info中存在该字段,即可自动映射;若不存在,此方法无效,需改用方法一。

替代方案:构造Azure AD用户头像URL

如果不想调用Graph API,可以通过Azure AD的公共头像URL格式构造:https://graph.microsoft.com/v1.0/users/{user-id}/photo/$value,其中{user-id}可从Azure AD返回的oid声明中获取。在Keycloak中添加Script Mapper实现:

var userId = user.getFederationIdentity().getToken().getOtherClaims().get("oid");
var avatarUrl = "https://graph.microsoft.com/v1.0/users/" + userId + "/photo/$value";
user.setSingleAttribute("picture", avatarUrl);

注意:此URL需要携带有效的Azure AD访问令牌才能访问,若前端直接使用,需确保请求时包含令牌,否则会返回401。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:20:35