首页 > 解决方案 > Javascript OneLogin Create Session Login Token returns No 'Access-Control-Allow-Origin'

问题描述

I am trying to get a session token from the one login api using a cross-domain request with javascript and chrome. The request fails with the following message:

Failed to load https://api.us.onelogin.com/api/1/login/auth: Response to 
preflight request doesn't pass access control check: No 'Access-Control- 
Allow-Origin' header is present on the requested resource. Origin ' 
<my_server_url>' is therefore not allowed access. The response had HTTP 
status code 404.

The code used to make the request is the following:

function get_session_token(user,pwd,domain)
{

  var method = "POST";
  var url = "https://api.us.onelogin.com/api/1/login/auth";

  var xhr = new XMLHttpRequest();
  xhr.withCredentials = True

  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      //response logic here...
   }
  }

  xhr.open(method, url, true);

  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.setRequestHeader("Authentication", "Bearer "+bearer);
  xhr.setRequestHeader("Custom-Allowed-Origin-Header-1", "<my_server_url>");

  body = {
    "username_or_email": user, 
    "password": pwd, 
    "subdomain": domain
  }

  xhr.send(JSON.stringify(body));
}

The request works correctly from Postman. Any idea on how to solve it?

标签: javascriptgoogle-chromecorsonelogin

解决方案


我不会深入探讨“为什么使用 CORS?”的细节。(因为跨站脚本攻击)但是如果你想知道为什么浏览器拒绝这个调用(这个错误是由你的浏览器产生的,而不是 OneLogin),只需谷歌 CORS。

答案是,当您第一次从 OneLogin 请求登录令牌时,您必须提供您从中进行 Javascript 调用的网页。

https://developers.onelogin.com/api-docs/1/login-page/create-session-login-token - 特别是Custom-Allowed-Origin-Header-1参数。

通过将此设置为您的网页发出 Javascript 请求的主机名,您可以指示 OneLogin 正确地让浏览器知道您可以跨域进行 Javascript 调用以获取资源。

将其设置为您的网页所在的域,它应该可以工作。


推荐阅读