当前位置:网站首页>Chapter 7 supporting CORS in rest services
Chapter 7 supporting CORS in rest services
2022-07-26 15:29:00 【yaoxin521123】
List of articles
Chapter vii. stay REST Support in the service CORS
summary
This section provides CORS An overview of and how to IRIS REST Enabled in service CORS Overview .
CORS brief introduction
Cross-domain resource sharing (CORS) Allow scripts running in another domain to access services .
Usually , When the browser runs a script from a domain , It allows for XMLHttpRequest call , But they are not allowed when calling another domain . This browser behavior restricts someone from creating malicious scripts that can abuse confidential data . Malicious scripts may allow a user to access information in another domain with the privileges granted to the user , But then when the user doesn't know , Use confidential information for other purposes . To avoid this safety problem , Browsers generally do not allow such cross domain calls .
Do not use cross domain resource sharing (CORS) Under the circumstances , Have access to REST The script of a web page service usually has to be provided with REST The server of the service is in the same domain . In some circumstances , Connect the web page with script and provide REST It is useful to put the server of the service in different domains . CORS Support this arrangement .
Here is how to use the browser CORS Handle XMLHttpRequest Simplified description of :
- Domain
DomOneThe script in the web page in contains a pair ofDomTwoIn domainIRIS RESTServiceXMLHttpRequest.XMLHttpRequesthaveCORSCustom headers for . - Users view this page and run scripts . The user's browser detected a domain different from the domain containing the web page
XMLHttpRequest. - The user's browser is directed to
IRIS RESTThe service sends a special request , The request indicatesXMLHttpRequestOfHTTPRequest method and the domain of the original web page , In this example isDomOne. - If the request is allowed , Then the response contains the requested information . otherwise , The response contains only instructions
CORSThe requested header is not allowed .
Enable REST Services to support CORS Overview
By default ,REST Service not allowed CORS header . however , Enable CORS Support . stay REST Enable pair CORS Support for has two parts :
- Enable
RESTService to receive some or allHTTPRequestedCORSheader .. - Write code , send
RESTService checkCORSRequest and decide whether to continue . for example , You can provide an allow list , It contains domains that contain only trusted scripts .IRISProvides a simple default implementation for document purposes ; This default implementation allows anyCORSrequest .
Important note : Default CORS Header processing is not applicable to processing confidential data REST service .
Accept CORS header
To specify REST Service acceptance CORS header :
- Modify the specification class to include
HandleCorsRequestParameters .
To enable for all calls CORS Header processing , Please put HandleCorsRequest Parameter specified as 1:
Parameter HandleCorsRequest = 1;
perhaps , To enable CORS Header processing , But not call , Please put HandleCorsRequest Parameter specified as “”( An empty string ):
Parameter HandleCorsRequest = "";
- If you will
HandleCorsRequestParameter specified as“”, Please editOpenAPI XDataBlock to indicate which calls supportCORS. say concretely , For the operation object , Add the following attribute names and values :
"x-ISC_CORS":true
for example ,OpenAPI XData A block may contain the following :
"post":{
"description":"Creates a new pet in the store. Duplicates are allowed",
"operationId":"addPet",
"produces":[
"application/json"
],
...
add to x-ISC_CORS attribute , As shown below :
"post":{
"description":"Creates a new pet in the store. Duplicates are allowed",
"operationId":"addPet",
"x-ISC_CORS":true,
"produces":[
"application/json"
],
...
- Compile the specification class . This operation regenerates the scheduling class , Lead to actual changes in behavior . There's no need to learn more about
dispatchclass , But please note the following changes :
- It now contains
HandleCorsRequestThe value of the parameter . URLMap XDataThe block now contains<Route>ElementalCors="true".
If HandleCorsRequest Parameter is 0( The default value is ), Disable for all calls CORS Header processing . under these circumstances , If REST Service received with CORS Header request , Then the service will reject the request .
Important note :IRIS REST Service support OPTIONS request (CORS Pre inspection request ), This request is used to determine REST Does the service support CORS. This request is always sent unauthenticated , And by the CSPSystem User execution . This user should have REST Of any database used by the service READ jurisdiction ; without , The service will respond HTTP 404 error .
Define how to handle CORS header
When you enable REST Service to accept CORS Header time , By default , The service accepts any CORS request . REST The service should check CORS Request and decide whether to continue . for example , You can provide an allow list , It contains domains that contain only trusted scripts . So , need :
- establish
%CSP.RESTSubclasses of . In this class , Implement theOnHandleCorsRequest()Method . - Modify the specification class and recompile , Regenerate scheduling class .
The end result is that the scheduling class is from the custom class rather than from %CSP.REST Inherit , So use right OnHandleCorsRequest() The definition of , It overrides the default CORS Header processing .
Definition OnHandleCorsRequest()
stay %CSP.REST In the subclass of , Definition OnHandleCorsRequest() Method , This method needs to be checked CORS Request and set the response header appropriately .
To define this method , Must be familiar with CORS Details of the agreement ( No discussion here ).
You also need to know how to check the request and set the response header . So , It is useful to check the default method used , namely %CSP.REST Of HandleDefaultCorsRequest() Method . This section explains how this method handles sources 、 The credentials 、 Headers and request methods and propose variations . You can use this information to write OnHandleCorsRequest() Method .
The following code gets the source and uses it to set the response header . One possible variant is to test the source according to the Allow list . Then the domain is allowed , Set the response header . If not , Please set the response header to an empty string .
#; Get the origin
Set tOrigin=$Get(%request.CgiEnvs("HTTP_ORIGIN"))
#; Allow requested origin
Do ..SetResponseHeaderIfEmpty("Access-Control-Allow-Origin",tOrigin)
The following lines specify that authorization headers should be included .
#; Set allow credentials to be true
Do ..SetResponseHeaderIfEmpty("Access-Control-Allow-Credentials","true")
The following line gets the header and request method from the incoming request . The code should test whether headers and request methods are allowed . If allowed , Please use them to set the response header . If not , Please set the response header to an empty string .
#; Allow requested headers
Set tHeaders=$Get(%request.CgiEnvs("HTTP_ACCESS_CONTROL_REQUEST_HEADERS"))
Do ..SetResponseHeaderIfEmpty("Access-Control-Allow-Headers",tHeaders)
#; Allow requested method
Set tMethod=$Get(%request.CgiEnvs("HTTP_ACCESS_CONTROL_REQUEST_METHOD"))
Do ..SetResponseHeaderIfEmpty("Access-Control-Allow-Method",tMethod)
Important note : Default CORS Header processing is not applicable to processing confidential data REST service .
Modify the specification class
In defining %CSP.REST The self defined subclass of ( Include OnHandleCorsRequest() The implementation of the ) after , Do the following :
- Edit
OpenAPI XDatablock , sendinfoObject contains ax-ISC_DispatchParentNew properties of . The value of this attribute must be the fully qualified name of the custom class .
for example , hypothesis OpenAPI XData The blocks are as follows :
"swagger":"2.0",
"info":{
"version":"1.0.0",
"title":"Swagger Petstore",
"description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification",
"termsOfService":"http://swagger.io/terms/",
"contact":{
"name":"Swagger API Team"
},
...
hypothesis %CSP.REST The self defined subclass of is named test.MyDispatchClass. under these circumstances , Will be modified XData block , As shown below :
"swagger":"2.0",
"info":{
"version":"1.0.0",
"title":"Swagger Petstore",
"description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification",
"termsOfService":"http://swagger.io/terms/",
"x-ISC_DispatchParent":"test.MyDispatchClass",
"contact":{
"name":"Swagger API Team"
},
...
- Compile the specification class . This operation regenerates the scheduling class . You will notice that this class now extends the custom scheduling superclass . So it will use
OnHandleCorsRequest()Method .
边栏推荐
- [basic] the difference between dynamic link library and static link library
- Practical task scheduling platform (scheduled task)
- anaconda No module named ‘cv2‘
- DICOM learning materials collection
- Continuous integration (II) introduction to the basic use of Jenkins
- 拒绝噪声,耳机小白的入门之旅
- R language ggplot2 visualization: use the ggballoonplot function of ggpubr package to visualize the balloon graph (visualize the contingency table composed of two classification variables), and config
- # 工欲善其事必先利其器-C语言拓展--嵌入式C语言(十一)
- [5 minutes paper] Pointer network
- VP video structured framework
猜你喜欢

How much help does solid state disk have for game operation

What is the transport layer protocol tcp/udp???

反射、枚举以及lambda表达式

If food manufacturing enterprises want to realize intelligent and collaborative supplier management, it is enough to choose SRM supplier system

食品制造企业想要实现智能协同的供应商管理,选择SRM供应商系统就够了

桌面应用布局图

Glyphicons V3 字体图标查询

【静态代码质量分析工具】上海道宁为您带来SonarSource/SonarQube下载、试用、教程

持续集成(一)基本概念简要介绍

【基础】动态链接库/静态链接库的区别
随机推荐
Where is the foreign literature needed to write the graduation thesis?
Devsecops, speed and security
# 工欲善其事必先利其器-C语言拓展--嵌入式C语言(十一)
anaconda No module named ‘cv2‘
C # set different text watermarks for each page of word
北京的大学排名
Continuous integration (I) brief introduction to basic concepts
食品制造企业想要实现智能协同的供应商管理,选择SRM供应商系统就够了
【LeetCode】33、 搜索旋转排序数组
QT is the most basic layout, creating a window interface
使用两个栈实现一个队列
企业数字化转型需要深入研究,不能为了转型而转型
Familiarize you with the "phone book" of cloud network: DNS
Desktop application layout
关于工控网关物联网串口转WiFi模块与串口转网口模块的选型
[leetcode] 33. Search rotation sort array
Practical task scheduling platform (scheduled task)
R language ggplot2 visualization: use ggplot2 to visualize the scatter diagram, and use the theme of ggpubr package_ The pubclean function sets the theme without axis lines in the visual image
FOC learning notes - coordinate transformation and simulation verification
兆骑科创高端人才项目引进落地,双创大赛承办,线上直播路演