如何在 angular 6 的生产级应用程序中处理 Cross-Origin 资源共享?
How to handle Cross-Origin Resource Sharing in a production level appliaction of angular 6?
我知道我可以通过修改服务器以添加 header Access-Control-Allow-Origin 来允许任何请求到达服务器。但是在生产级别这样做是否安全。还是有其他安全的方法来做到这一点?
通常,您只需将允许的主机列入白名单,如果您使用express
,这可以是以下代码。
const cors = require('cors');
const whitelist = [
'https://myfrontserver1.com',
'https://myfrontserver2.com',
'https://myfrontserver3.com',
]; // the white list could be extracted from database, or a config file is up to you
app.use(cors({ origin: whitelist, credentials: true }));
解释 CORS。
对于每个 XHR(XMLHttpRequest) 请求,浏览器都会向服务器发送一个 pre-flight 请求,并使用适当的 headers 来检查服务器是否允许实际请求。如果您不添加任何处理程序,那么它将在浏览器上抛出异常。
要在 Spring 启动时处理此问题,您可以在控制器方法或 class(使其成为全局)上添加以下注释来处理请求:-
@CrossOrigin(
origins = { "*" }, // You can add your allowed origins here
methods = { RequestMethod.GET }, // Request Method
allowCredentials = "true",
allowedHeaders = CorsConfiguration.ALL, // Allowed Headers
exposedHeaders = {})
@RequestMapping(method = RequestMethod.POST)
public String greeting(@RequestBody SomeClass
name) {
// your own code
}
您也可以查看this以供参考
我知道我可以通过修改服务器以添加 header Access-Control-Allow-Origin 来允许任何请求到达服务器。但是在生产级别这样做是否安全。还是有其他安全的方法来做到这一点?
通常,您只需将允许的主机列入白名单,如果您使用express
,这可以是以下代码。
const cors = require('cors');
const whitelist = [
'https://myfrontserver1.com',
'https://myfrontserver2.com',
'https://myfrontserver3.com',
]; // the white list could be extracted from database, or a config file is up to you
app.use(cors({ origin: whitelist, credentials: true }));
解释 CORS。
对于每个 XHR(XMLHttpRequest) 请求,浏览器都会向服务器发送一个 pre-flight 请求,并使用适当的 headers 来检查服务器是否允许实际请求。如果您不添加任何处理程序,那么它将在浏览器上抛出异常。
要在 Spring 启动时处理此问题,您可以在控制器方法或 class(使其成为全局)上添加以下注释来处理请求:-
@CrossOrigin(
origins = { "*" }, // You can add your allowed origins here
methods = { RequestMethod.GET }, // Request Method
allowCredentials = "true",
allowedHeaders = CorsConfiguration.ALL, // Allowed Headers
exposedHeaders = {})
@RequestMapping(method = RequestMethod.POST)
public String greeting(@RequestBody SomeClass
name) {
// your own code
}
您也可以查看this以供参考