【问题标题】:Okta API or standard CURL/ajax problemsOkta API 或标准 CURL/ajax 问题
【发布时间】:2017-05-14 12:54:04
【问题描述】:

我希望从 Okta API 中提取当前用户的登录名,但我通常只是一个 HTML/CSS 人,所以我很挣扎。我目前对此感到困惑:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery.ajax({
    url: "https://harmelin.okta.com/api/v1/users/me",

    type: 'GET',
    dataType: 'json',
    contentType: 'application/json',
    processData: false,
    success: function (data) {
      alert(JSON.stringify(data));
    },
    error: function(){
      alert("Cannot get data");
    }
});

</script>
</head>

<body>
<script type="text/javascript">
    document.write(data.profile.login);
</script>
</body>

我过去曾将部分代码与其他 API 一起使用,但不得不对其进行一些修改。我知道我的问题是授权,因为我收到 403 错误。 Okta 文档将此作为请求示例:

curl -v -X GET \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: SSWS ${api_token}" \
"https://${org}.okta.com/api/v1/users/me"

如何在我的脚本中获得授权?这会为我提供未来发展所需的东西(data.profile.login)吗?

【问题讨论】:

    标签: jquery ajax curl okta


    【解决方案1】:

    您应该不在来自浏览器的请求中包含 SSWS 令牌。任何阅读您页面源代码的人都可以使用它来修改您的组织。

    如果您收到 403,那是因为用户未登录或未发送 cookie。

    如果用户未登录,则应使用the okta-signin-widget、okta-auth-js 或your login page 登录。

    在您的情况下,cookie 没有被发送,因为它是一个 CORS 请求。默认情况下,jQuery 不会在跨域请求中发送 cookie。您可以通过在请求中发送 withCredentials 来解决此问题。

    用户登录后,以下请求应该可以工作:

    jQuery.ajax({
        url: "https://harmelin.okta.com/api/v1/users/me",
        type: 'GET',
        dataType: 'json',
        contentType: 'application/json',
        xhrFields: {
            withCredentials: true
        },
        success: function (data) {
            alert(JSON.stringify(data));
        },
        error: function(err){
            alert(JSON.stringify(err));
        }
    });
    

    【讨论】:

    • 正是我想要的。谢谢。
    【解决方案2】:

    你应该添加

    (代码未测试)

    headers: {
         "Authorization": "SSWS ${api_token}",
         "Content-Type": "application/json",
         "Accept": "application/json"
    
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-15
      • 2014-09-13
      • 2013-08-06
      • 1970-01-01
      • 2012-02-15
      • 2018-12-28
      • 1970-01-01
      相关资源
      最近更新 更多