使用CORS保护API [英] Protect API with CORS

查看:56
本文介绍了使用CORS保护API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用CORS保护我的API.我希望我的API仅具有来自所选域的呼叫访问权限.

I would like to protect my API with CORS. I want my API to have call access only from the selected domain.

我正在使用node.js进行表达,因此我将其添加到我的项目中: https://github.com/expressjs/cors

I am using node.js and express, so I add to my project: https://github.com/expressjs/cors

和示例代码:

var express = require('express')
var cors = require('cors')
var app = express()

var corsOptions = {
  origin: 'http://example.com',
  optionsSuccessStatus: 200
}

app.get('/test', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for only example.com.'})
})

但是,如果我通过POSTMAN从本地主机发出请求,我仍然会从该路由中获得响应.应该将其阻止,并且仅适用于来自一个域(example.com)的请求.

But if I make a request via POSTMAN from localhost, I still get a response from this routing. This should be blocked and only work for requests from one domain (example.com).

我之前尝试过:

router.get('/test', cors(corsOptions), function(req, res, next) {
  console.log(corsOptions);
  res.header("Access-Control-Allow-Origin", "http://www.example.com);
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.status(200).send({ work: true });
});

但这也使我从POSTMAN发出的请求...

But this also lets my requests from POSTMAN...

我希望有一个仅在我的example.com页上并且从JavaScript发送请求时才可以引用的API.

I would like to have an API that can be referenced only if it comes to my example.com page and from there are requests sent by JavaScript.

推荐答案

COR仅在浏览器中有效,因此它不会对来自Postman之类的浏览器之外的请求产生任何影响.这是一项需要客户端自己实施CORs保护的技术.

CORs only works from browsers so it will not have any effect on a request made outside a browser like from Postman. It is a technology that requires the client itself to implement the CORs protection.

除非实现了某种身份验证或基于时间的令牌,否则无法阻止POSTMAN或任何其他程序访问使用您的API.这是基于Web的API的本质.如果可以在您的网页中使用它们,那么其他任何人也可以通过编程方式使用它们.

There is no way to keep POSTMAN or any other programmatic access from using your API unless you implement some sort of authentication or time-based tokens. This is the nature of web-based APIs. If they can be used in your web pages, then anyone else can use them programmatically too.

COR的目的是防止其他网页使用其自己的网页Javascript中的API.这就是它所保护的全部.实际上,如果另一个网站希望从其服务器访问您的API,然后将结果放入自己的网页中,则他们可以做到这一点-COR完全不限制浏览器外部的服务器或编程访问.

The purpose of CORs is to keep other web pages from using your API from their own web page Javascript. That's ALL it protects. In fact, if another web site wants to access your API from their server and then put results into their own web pages, they can do that - CORs does not restrict server or programmatic access outside a browser at all.

有关保护API的一般主题的进一步讨论,请参见以下参考文献:

For further discussion of the general topic of protecting an API, see these references:

保护Express API

只有您的网络服务器可以安装的设置API看到

jQuery ajax安全性

这篇关于使用CORS保护API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆