pablogg
(Pablo)
2020 年4 月 12 日 16:51
1
我昨天升级了 Discourse,随后所有 API 回调都报错了。我发现问题是出在认证头(1)上,但我尝试了一些调用,却得到了以下错误:
Access to XMLHttpRequest at 'https://mydomain.com/notifications.json?username=admin' from origin 'https://mydomain.com' has been blocked by CORS policy: Request header field api-username is not allowed by Access-Control-Allow-Headers in preflight response.
我使用的是 Vue,并已按如下方式将 api-key 和 api-username 添加到请求头中:
Vue.http
.get(
"https://discourse.mydomain.com/notifications.json?username="+input.username,
{
headers: {
"Api-Key":"xxxxxxxxxxxxxxxxx",
"Api-Username": "system",
"content-type": "application/json",
accept: "application/json"
}
}
)
(1) Discourse REST API Documentation
pablogg
(Pablo)
2020 年4 月 12 日 17:54
3
是的,我已经在 Discourse 设置中添加了调用 API 的域名,但关于字段 api-username 的错误,我不知道该如何解决。
RGJ
(Richard - Communiteq)
2020 年4 月 12 日 18:05
4
你竟然把 system API 密钥放在客户端代码中?
这意味着任何人都可以从你的 JavaScript 代码中获取它,并完全掌控 你的论坛。
任何发往 Discourse 的 Ajax HTTP 请求都应利用现有会话,或者根本不需要会话。
3 个赞
pablogg
(Pablo)
2020 年4 月 12 日 18:09
5
不仅仅是测试,我正在使用用户名
Vue.http
.get(
"https://discourse.mydomain.com/notifications.json?username="+input.username,
{
headers: {
"Api-Key":"xxxxxxxxxxxxxxxxxxxxxx",
"Api-Username": input.username
}
}
)
但我仍然遇到相同的 CORS 错误以及 api-username 字段的问题。
1 个赞
blake
(Blake Erickson)
2020 年4 月 12 日 18:24
7
您确实不应该将这些 API 凭据用于 CORS 请求,这就是为什么不允许该标头字段。
Oh, so you are trying to make this request from a client-side javascript application? That is not permitted for numerous reasons. For example, if you include an admin API key in the source code of your javascript app, any user could gain full admin access to your forum. Here is a previous topic on the subject.
不过,我们允许在 CORS 中使用 user-api 标头:
I’m trying to post comments to my Discourse instance from another web application using user api keys. I managed to get the user key following the method described in your original topic and this other useful discussion .
After getting the key, when I send it along with my requests as a value of the User-Api-Key header, I get the Request header field User-Api-Key is not allowed by Access-Control-Allow-Headers error.
As I asked in my PR , I’m not sure if it’s enough to add the headers in the file…
3 个赞
pablogg
(Pablo)
2020 年4 月 12 日 19:14
8
我已经阅读了 用户 API 密钥规范 …
在我的情况下,我使用带有 JavaScript 前端应用的 SSO。我能否在不为每个用户显示授权 UI 的情况下调用 API?我希望有一种方法可以使用 api-username… 这是否可行?
此致
pablogg
(Pablo)
2020 年7 月 22 日 07:27
10
最终,我回退到了 Discourse 的旧版本,这样就不必修改所有的 API 集成。