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

使用amazon-cognito-identity.min.js获取Cognito用户自定义属性遇权限错误

问题:Amazon Cognito调用getUserAttributes()返回「User is not authorized」

已基于amazon-cognito-identity.min.js实现用户认证功能,登录、获取JWT Token均正常,但调用cognitoUser.getUserAttributes()获取用户自定义属性时,触发「User is not authorized」错误,无法获取属性。

相关代码如下:

登录逻辑代码:

var userPoolId = 'eu-west-1_xxxxxxxx'
var clientId = 'yyyyyyyyyyyyyyyyyyyyyyyyyy'

var poolData = { UserPoolId : userPoolId,
ClientId : clientId
};

var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);

function login(){
    var username = $('#username').val();
    var authenticationData = {
        Username: username,
        Password: $('#password').val()
    };

    console.log("Username:",username, "Password:",$('#password').val())

    var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);

    var userData = {
        Username : username,
        Pool : userPool
    };
    var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
    console.log(cognitoUser);

    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function (result) {
            console.log(result)
            var accessToken = result.getAccessToken().getJwtToken();
           

            cognitoUser.getUserAttributes(function(err, result) {
                if (err) {
                    alert(err.message || JSON.stringify(err));
                    return;
                }
                custom_attribute = result[4].getValue();
                console.log(custom_attribute);
                return custom_attribute;
               
        });

            localStorage;
            localStorage.setItem("accessToken", accessToken);
            localStorage.setItem("custom_attribute", custom_attribute);            
            window.location = './index.html';
        },

        onFailure: function(err) {
            console.log("failed to authenticate");
            console.log(JSON.stringify(err))
            alert("Failed to Log in.\nPlease check your credentials.")
        },
    });
}

function checkLogin(redirectOnRec, redirectOnUnrec){

    var cognitoUser = userPool.getCurrentUser();
    if (cognitoUser != null) {
        if (redirectOnRec) {
            window.location = './index.html';
        } else {
            $("#body").css({'visibility':'visible'});           
        }
    } else {
        if (redirectOnUnrec) {
            window.location = './signin.html'
        } 
    }
}

function logOut() {
    
    var cognitoUser = userPool.getCurrentUser();
    console.log(cognitoUser, "signing out...")
    cognitoUser.signOut();
    window.location = './signin.html';
}

var idKey = 'cognito-idp.ap-southeast-2.amazonaws.com/' + userPoolId
var cognitoUser = userPool.getCurrentUser();

index.html触发代码:

<script type="text/javascript">
      $(function () {        
        checkLogin(false, true)
      })
      window.onload = function () {
        checkLogin(false, true)
        localStorage;
        var token = localStorage.getItem("accessToken");
      }
    </script>

解决方案

1. 修复异步逻辑顺序问题

原登录回调中,getUserAttributes()是异步操作,但后续直接执行localStorage.setItem和页面跳转,会导致属性未获取完成就跳转,同时可能打断请求。调整代码,确保在属性获取完成后再执行存储和跳转:

cognitoUser.authenticateUser(authenticationDetails, {
  onSuccess: function (result) {
    var accessToken = result.getAccessToken().getJwtToken();

    cognitoUser.getUserAttributes(function(err, attributes) {
      if (err) {
        alert(err.message || JSON.stringify(err));
        return;
      }
      // 避免依赖索引遍历属性(索引可能随属性数量变化)
      let custom_attribute = null;
      attributes.forEach(attr => {
        if (attr.getName() === 'custom:your_attribute_name') { // 替换为你的自定义属性名
          custom_attribute = attr.getValue();
        }
      });
      
      localStorage.setItem("accessToken", accessToken);
      localStorage.setItem("custom_attribute", custom_attribute);            
      window.location = './index.html';
    });
  },
  onFailure: function(err) {
    console.log("failed to authenticate");
    console.log(JSON.stringify(err))
    alert("Failed to Log in.\nPlease check your credentials.")
  },
});

2. 确保用户会话有效(针对非登录场景)

如果是通过userPool.getCurrentUser()获取用户对象调用getUserAttributes(),必须先验证会话有效性:

var cognitoUser = userPool.getCurrentUser();
if (cognitoUser) {
  cognitoUser.getSession(function(err, session) {
    if (err) {
      alert(err.message || JSON.stringify(err));
      return;
    }
    // 会话有效后再获取属性
    cognitoUser.getUserAttributes(function(err, attributes) {
      if (err) {
        alert(err.message || JSON.stringify(err));
        return;
      }
      // 处理属性
      attributes.forEach(attr => {
        console.log(`${attr.getName()}: ${attr.getValue()}`);
      });
    });
  });
}

3. 检查Cognito用户池配置

  • 应用客户端权限:登录AWS控制台,进入目标用户池 → 应用客户端 → 确认「允许的OAuth范围」包含profile;同时在「读属性权限」中勾选需要获取的自定义属性。
  • 自定义属性权限:进入用户池 → 属性 → 自定义属性,确认目标属性开启了「用户可读取」权限(用户自己读取属性需要此设置)。
  • 属性命名规范:自定义属性必须以custom:开头(如custom:user_role),确保代码中使用的属性名与配置一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:01:07