javascript - 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?
解决方案
我不会深入探讨“为什么使用 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 调用以获取资源。
将其设置为您的网页所在的域,它应该可以工作。
推荐阅读
- c - 函数中动态分配的结构
- machine-learning - 为什么要在机器学习中连接特征?
- jquery - 单击按钮并通过 jquery 更改为不同的网页后,用图像填充 css 网格
- c - 如何做一个ANSI颜色代码
- c# - 无法使用另一个 .exe 启动 .exe
- php - 使用 supervisord 运行多个 php 实例,但运行任务的一半
- python - 如何在不删除先前对象的情况下更新 Django 中的多对多字段?
- python - 无法从某些 html 元素中抓取特定部分的文本
- java - OutOfMemoryError 位图到 Base64 字符串
- xml - 如何通过 Select-Xml 获取属性值?