In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Many novices are not very clear about how to build the second-generation gateway GateWay. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can get something.
GateWay, the second-generation gateway of Spring Cloud, is developed by pure Netty, and the underlying layer is built by Reactor,WebFlux, which does not rely on any Servlet container. Unlike Zuul, it uses asynchronous IO, and its performance is 1.6 times higher than that of Zuul. The construction process is as follows (this is a sub-project, and the main project can refer to the Nacos build process)
Pom
Org.springframework.cloud spring-cloud-starter-gateway com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery
Configuration file
Server: port: 8040spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: discovery: locator: enabled: true
The above means not only to register yourself with nacos, but also to get all the registration services of nacos.
Start the gateway project and you can now route the network. The access format is ip: Port / service registration name / restfulapi-url
For example, we now have two microservice projects, one for user (port 8082) and one for nacos (port 8081).
Three core concepts
The basic elements of Route (routing) Spring Cloud Gateway can be understood simply as a forwarding rule. Contains: ID, the URL,Predicate collection of the target and the Filter collection.
Predicate (predicate) means that java.util.function.Predicate,Spring Cloud Gateway uses Predicate to implement the matching condition of a route. This is a functional interface that can judge conditions. You can refer to my blog Java functional programming for details.
Filter (filter) modify request and response.
Since we used nacos for service discovery, we used the previous configuration file, but if we did not use service discovery, we would only do the following regular forwarding
Spring: cloud:gateway: routes:-id: some_route uri: http://www.baidu.com predicates:-Path=/user/1 filtes:-AddRequestHeader=X-Request-Foo, Bar
What this configuration means is that when we request the url of / user/1, we add AddRequestHeader=X-Request-Foo, Bar filter to do some processing, and then route to http://www.baidu.com.
Routing predicate configuration factory
Routing predicates configure different situations in which the factory is configured by a set of predicates.
Predicate factory remarks After this predicate matches requests that occur after the current date and time. Before this predicate matches requests that occur before the current date and time. Between this predicate matches requests that occur after datetime1 and before datetime2. The datetime2 parameter must come after datetime1. CookieCookie Route Predicate Factory has two parameters, the cookie name and the regular expression. This predicate matches the cookie with the given name and the value matches the regular expression. HeaderHeader Route Predicate Factory has two parameters, the title name and the regular expression. Matches the header with the given name and the value matches the regular expression. HostHost Route Predicate Factory takes one parameter: hostname mode. This pattern is an Ant style pattern. As a delimiter. This predicate matches the Host header that matches the pattern. MethodMethod Route Predicate Factory takes one parameter: the HTTP method to match. The Path matches the requested pathQueryQuery Route Predicate Factory with two parameters: a required parameter and an optional regular expression. RemoteAddrRemoteAddr Route Predicate Factory takes a list of CIDR symbol (IPv4 or IPv6) strings (with a minimum value of 1), for example, 192.168.0.1 and 16 (where 192.168.0.1 is the IP address and 16 is the subnet mask).
Route to the specified URL
Universal matching
Now let's remove the configuration of nacos and let nacos not find out.
Spring: application: name: gateway cloud: gateway: routes:-id: gateuri: http://127.0.0.1:8082predicates: # matches the jump by / user-Path=/user/**filters: # omit the first wildcard after the jump-StripPrefix=1
Visit at this time
Will jump to
Predicate After
Spring: application: name: gateway cloud: gateway: routes:-id: gateuri: http://127.0.0.1:8082predicates: # matches the jump by / user-Path=/user/**# allows the forward-After=2019-12-14T20:26:15.667+08:00 [Asia/Shanghai] filters: # omits the first wildcard-StripPrefix=1 after the jump occurs after 20: 26 on 2019-12-14
This means that forwarding is allowed after that time, if we set the time to
Spring: application: name: gateway cloud: gateway: routes:-id: gateuri: http://127.0.0.1:8082predicates: # matches the jump by / user-Path=/user/**# allows the forward-After=2019-12-15T20:26:15.667+08:00 [Asia/Shanghai] filters: # omits the first wildcard-StripPrefix=1 after jumping after 20: 26 on 2019-12-15
The forwarding failed and 404 was returned.
We can get the time settings here in the following ways
Public class TimeTest {public static void main (String [] args) {System.out.println (ZonedDateTime.now ());}}
Running result
2019-12-14T20:43:34.755+08:00 [Asia/Shanghai]
Predicate Before
Now let's change the number 15 above to Before.
Spring: application: name: gateway cloud: gateway: routes:-id: gateuri: http://127.0.0.1:8082predicates: # matches the jump by / user-Path=/user/**# allows the forward-Before=2019-12-15T20:26:15.667+08:00 [Asia/Shanghai] filters: # omits the first wildcard-StripPrefix=1 after the jump until 20:26 on 2019-12-15
At this point, it can be forwarded normally, while changing it to the 14th will fail.
Predicate Between
Spring: application: name: gateway cloud: gateway: routes:-id: gateuri: http://127.0.0.1:8082predicates: # matches the jump by / user-Path=/user/**# allows the forward-Between=2019-12-14T20:26:15.667+08:00 [Asia/Shanghai] between 20:26 on 2019-12-14 and 20:26 on 2019-12-15 2019-12-15T20:26:15.667+08: 00 [Asia / Shanghai] filters: # omit the first wildcard after the jump-StripPrefix=1
Predicate Cookie
We add a Controller with cookie to the user module
@ Slf4j@RestControllerpublic class CookieController {@ GetMapping ("/ welcome") public Boolean handle (HttpServletRequest request, HttpServletResponse response) throws Exception {Cookie cookie = new Cookie ("test", "value"); cookie.setMaxAge (Integer.MAX_VALUE); response.addCookie (cookie); log.info ("welcome"); return true;}}
At this point, we visit the Controller as
At this time, the gateway side is configured as
Spring: application: name: gateway cloud: gateway: routes:-id: gateuri: http://127.0.0.1:8082predicates: # matches the jump by / user-Path=/user/**# is only allowed to be forwarded with a cookie whose Cookie name is test and the value matches the regular value-Cookie=test,valuefilters: # omit the first wildcard-StripPrefix=1 after the jump
Predicate Header
Now let's add a Controller method to the user module
@ GetMapping ("/ header") public String header (@ RequestHeader ("item") String item) {return item;}
We add a request header to the access to the method through postman
The configuration in the gateway is
Spring: application: name: gateway cloud: gateway: routes:-id: gateuri: http://127.0.0.1:8082predicates: # the jump is matched by / user-Path=/user/**# will be forwarded only if the request header name is item and the value matches the regular 123.p.-Header=item,123.pfilters: # omit the first wildcard-StripPrefix=1 after the jump
It's regular here. Can match a single character
If we set the wrong character in the request header item, we cannot forward it.
Predicate Host
To configure Host, we need to add a domain name mapping to the server's hosts file, and of course we need a domain name for DNS resolution on the Internet.
I will add my domain name as local.register.com here.
Access the find method of user
Add configuration to the gateway
Spring: application: name: gateway cloud: gateway: routes:-id: gateuri: http://127.0.0.1:8082predicates: # matches the jump by / user-Path=/user/**# can omit the first wildcard-StripPrefix=1 only if the request header Host is taken and the value matches *. Register.com:8040 can be omitted by forwarding-Host=**.register.com:8040filters: # after the jump
At this point, we visit the following through the gateway
Predicate Method
Spring: application: name: gateway cloud: gateway: routes:-id: gateuri: http://127.0.0.1:8082predicates: # matches the jump by / user-Path=/user/**# can be forwarded only if the HTTP request method is GET-Method=GETfilters: # omit the first wildcard after the jump-StripPrefix=1
Predicate Query
Now let's add a Controller method to the user module
@ GetMapping ("/ query") public String query (@ RequestParam ("name") String name) {return name;}
Visit as follows
The gateway is configured as follows
Spring: application: name: gateway cloud: gateway: routes:-id: gateuri: http://127.0.0.1:8082predicates: # Jump is matched by / user-Path=/user/**# can be omitted by forwarding-Query=namefilters: # the first wildcard-StripPrefix=1 only if the request has the parameter name name.
Cannot be forwarded without this parameter, such as
Predicate RemoteAddr
Spring: application: name: gateway cloud: gateway: routes:-id: gateuri: http://127.0.0.1:8082predicates: # matches the jump by / user-Path=/user/**# will be forwarded only if the request is a 192.168.20.1 IP address from 192.168.20.1 to 192.168.20.254. .1 / 24filters: # omit the first wildcard after the jump-StripPrefix=1
For example
But it cannot be accessed with 127.0.0.1
Now we restore nacos's service discovery.
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-StripPrefix=1
To distinguish it from not doing any configuration, we write user-center here in the predicate Path
Custom routing predicate factory
Suppose one of our API is only allowed to forward between 9: 00 a.m. and 5: 00 p.m.
The configuration file is as follows
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**-TimeBetween= 9:00 in the afternoon, 5:00filters: # omit the first wildcard after the jump-StripPrefix=1
Since this TimeBetween is not the default predicate factory for gateway, we need to implement a predicate factory ourselves. Let's first define a time configuration class.
@ Datapublic class TimeBetweenConfig {private LocalTime start; private LocalTime end;}
Then customize a predicate factory class whose name must begin with a custom predicate (in this case, TimeBetween), end with RoutePredicateFactory, and inherit the AbstractRoutePredicateFactory abstract class
@ Componentpublic class TimeBetweenRoutePredicateFactory extends AbstractRoutePredicateFactory {public TimeBetweenRoutePredicateFactory () {super (TimeBetweenConfig.class);} @ Override public Predicate apply (TimeBetweenConfig config) {LocalTime start = config.getStart (); LocalTime end = config.getEnd (); return exchange-> {LocalTime now = LocalTime.now (); return now.isAfter (start) & & now.isBefore (end);} @ Override public List shortcutFieldOrder () {return Arrays.asList ("start", "end");}}
Built-in filter factory
1 AddRequestHeader GatewayFilter Factory
2 AddRequestParameter GatewayFilter Factory
3 AddResponseHeader GatewayFilter Factory
4 DedupeResponseHeader GatewayFilter Factory
5 Hystrix GatewayFilter Factory
6 FallbackHeaders GatewayFilter Factory
7 PrefixPath GatewayFilter Factory
8 PreserveHostHeader GatewayFilter Factory
9 RequestRateLimiter GatewayFilter Factory
10 RedirectTo GatewayFilter Factory
11 RemoveHopByHopHeadersFilter GatewayFilter Factory
12 RemoveRequestHeader GatewayFilter Factory
13 RemoveResponseHeader GatewayFilter Factory
14 RewritePath GatewayFilter Factory
15 RewriteResponseHeader GatewayFilter Factory
16 SaveSession GatewayFilter Factory
17 SecureHeaders GatewayFilter Factory
18 SetPath GatewayFilter Factory
19 SetResponseHeader GatewayFilter Factory
20 SetStatus GatewayFilter Factory
21 StripPrefix GatewayFilter Factory
22 Retry GatewayFilter Factory
23 RequestSize GatewayFilter Factory
24 Modify Request Body GatewayFilter Factory
25 Modify Response Body GatewayFilter Factory
26 Default Filters
AddRequestHeader
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 192.168.10.172:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-StripPrefix=1# adds a name to X-Request-Foo Request header with a value of Bar-AddRequestHeader=X-Request-Foo,Bar
It should be noted that the new request header is added after forwarding, so we cannot find it in the browser when we request the gateway. We can use command+N (idea is Ctrl+N in Windows) to find the NettyRoutingFilter class, and set a breakpoint in the filter method. You can see that it has been added in the following figure.
AddRequestParameter
Because there is such a method in the user module
@ GetMapping ("/ query") public String query (@ RequestParam ("name") String name) {return name;}
So when we configure the gateway
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-StripPrefix=1# adds a name to name Request parameter with a value of locky-AddRequestParameter=name,locky
Therefore, when we request in the gateway, we can access directly without writing parameters.
AddResponseHeader
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-StripPrefix=1# adds a name to X-Response-Foo Response header with the value of Bar-AddResponseHeader=X-Response-Foo, Bar
DedupeResponseHeader
The new features provided by Spring Cloud Greenwich SR2 are not available in this version.
Its main function is to remove weight, for example
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # Jump is matched by / user-center-Path=/user-center/**-Cookie=test,valuefilters: # omit the first wildcard after the jump-StripPrefix=1# is deduplicated in the Http response header Deretarget is a cross-domain request-DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
Hystrix
Hystrix is a fault-tolerant component in the first generation of Spring Cloud, but it has entered maintenance mode. In the future, Hystrix will be removed by Spring Cloud and replaced by Alibaba Sentinel/Resilience4J.
There are no specific settings here.
FallbackHeaders
It is also a support for Hystrix, so we don't need to make specific settings.
PrefixPath
To prefix the matching routes, we add a layer of access paths to the find of the user module
@ GetMapping ("/ test/find") @ SuppressWarnings ("unchecked") public Result findStr () {log.info ("access successful"); return Result.success (new User (1, "Zhang San", 23));}
Gateway configuration
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-add the prefix / test-PrefixPath=/test after the StripPrefix=1# jump
Then
Vs.
Consistent.
PreserveHostHeader
If not, the Header named Host is controlled by Http Client; if so, a request property (preserveHostHeader=true) is set, and the route filter checks to determine whether to send the original Header named Host. This is mainly about whether the Host attribute in the request header is forwarded to the proxy server through the gateway.
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard-StripPrefix=1# to forward the client's request message after the jump Header Host to backend proxy server-PreserveHostHeader
RequestRateLimiter
Gateway comes with current limiting service, but later we will integrate Gateway and Sentinel to limit current and circuit breaker.
RedirectTo
Forward to the backend service and then redirect to a url.
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-StripPrefix=1# forward to Path And carry a http://www.baidu.com to Location response header-RedirectTo=302, http://www.baidu.com
As can be seen from the above picture, we actually asked for http://127.0.0.1:8040/user-center/find, but we were redirected to Baidu. Here, the HTTP status code should be a sequence of HTTP status codes, such as 301.302. For specific status codes, please refer to HTTP protocol.
RemoveHopByHopHeadersFilter
Remove the Header that forwards the request. Multiple requests are separated by ",". The following Header is removed by default.
Connection
Keep-Alive
Proxy-Authenticate
Proxy-Authorization
TE
Trailer
Transfer-Encoding
Upgrade
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-StripPrefix=1 filter: # remove Forward request remove-hop-by-hop: headers: Keep-Alive Connection
RemoveRequestHeader
Remove the original request header
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-StripPrefix=1# removes the original request header X-Request-Foo-RemoveRequestHeader=X-Request-Foo
From the role of the spring cloud zuul gateway, we need to remove these request headers in cross-domain forwarding.
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-StripPrefix=1# removes the original cross-domain request header -RemoveRequestHeader=Access-Control-Allow-Origin filter: # remove forwarding request remove-hop-by-hop: headers: Access-Control-Allow-Credentials Access-Control-Allow-Origin,Vary,X-Frame-Options,token
RemoveResponseHeader
Remove response header
We add a Controller method to user
@ GetMapping ("/ addhead") public String addHeader (HttpServletRequest request, HttpServletResponse response) {response.addHeader ("X-Response-Foo", "Foo"); return "header";}
Gateway configuration
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-StripPrefix=1# remove response header X-Response-Foo-RemoveResponseHeader=X-Response-Foo
Through gateway forwarding, we can see the response header without this X-Response-Foo.
RewritePath
Rewrite request path
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # Jump is matched by / user-center-Path=/user-center/**filters: # is configured as the original path regular, and the rewritten path's regular-RewritePath=/user-center/ (?. *) / $\ {segment}
The above configuration will change / user-center/find to / find and forward it.
Direct access to user
Requested by the gateway
RewriteResponseHeader
Rewrite the response header and modify it according to the rule
There was a Controller method in user before.
@ GetMapping ("/ addhead") public String addHeader (HttpServletRequest request, HttpServletResponse response) {response.addHeader ("X-Response-Foo", "Foo"); return "header" } spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # Jump is matched by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-StripPrefix=1# rewrite response header X-Response-Foo has a value Foo of dee Content can be matched according to the rule-RewriteResponseHeader=X-Response-Foo,Foo,dee
The value of the / addhead,X-Response-Foo response header for accessing user is Foo.
The value of the / addhead,X-Response-Foo response header accessed through the gateway is dee
SaveSession
The WebSession::save operation is enforced before forwarding to the back-end microservice request. For things like Spring Session deferred data storage (the data is not immediately persisted), and you want to ensure that the session state is saved before the request is forwarded.
Now let's configure user to share Session and add dependencies
Org.springframework.boot spring-boot-starter-data-redis org.springframework.session spring-session-data-redis redis.clients jedis 2.9.0
Add configuration
Spring: redis: host: 127.0.0.1 port: 6379 password: xxxxx timeout: 10000 lettuce: pool: min-idle: 0 max-idle: 8 max-active: 8 max-wait:-1
Enable shared Session in SpringBoot
@ EnableRedisHttpSession@SpringBootApplicationpublic class UserApplication {public static void main (String [] args) {SpringApplication.run (UserApplication.class, args);}}
Add the following Controller to user
@ RestControllerpublic class SessionController {@ GetMapping ("/ first") public Map firstResp (HttpServletRequest request,HttpServletResponse response) {Map map = new HashMap (); request.getSession () .setAttribute ("request Url", request.getRequestURL ()); map.put ("request Url", request.getRequestURL ()); return map;} @ GetMapping ("/ sessions") public Object sessions (HttpServletRequest request,HttpServletResponse response) {Map map = new HashMap () Map.put ("SessionId", request.getSession (). GetId ()); map.put ("message", request.getSession (). GetAttribute ("request Url")); return map;}}
We start two user instances, one with a port number of 8082 and one with a port of 8083, and visit the following
We can see that except for the different RequestURL stored in Session, their SessionId is the same, indicating that this is a shared Session.
If we do not modify the gateway configuration, we will access it through the gateway
When accessing first, it will load balance these two instances, but we can see that it stores private network IP in Session instead of 127.0.0.1.
Do the following configuration at the gateway
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-save Session-SaveSession before forwarding the StripPrefix=1# request
At present, it has not been determined that it has much effect. On the contrary, it will destroy Session's data. Therefore, it is not recommended to increase this setting.
SecureHeaders
Add a series of security response headers.
The following Header (including values) is added by default:
1: delete the detected malicious code, if the X-XSS-Protection field is not seen in the response message, then the browser will assume that X-XSS-Protection is configured as 1, which is the browser's default setting of .1; mode=block: if malicious code is detected, it will not render malicious code.
Strict-Transport-Security:max-age=631138519 A website accepts a request from a HTTP and then jumps to HTTPS, where the user may talk to the server in an unencrypted way, such as typing http://foo.com or directly foo.com, before starting the jump. In this way, there is a potential threat of man-in-the-middle attack, and the jump process may be used by malicious websites to directly contact user information, rather than the original encrypted information. The website notifies the browser via HTTP Strict Transport Security that it is forbidden to use HTTP to load, and the browser should automatically replace all requests that try to use HTTP with HTTPS requests.
X-Frame-Options:DENY click hijacking (ClickJacking) is a visual deception. The attacker uses a transparent iframe to overwrite a web page, and then induces the user to operate on the web page, where the user will unknowingly click on the transparent iframe page. By repositioning the iframe page, you can induce the user to click right on some of the functional buttons on the iframe page.
The X-Frame-Options in the HTTP response header indicates whether the browser should load a page in iframe. If there is no X-Frame-Options in the server response header information, then the website is at risk of ClickJacking attack. A website can prevent click hijacking by setting X-Frame-Options to prevent pages within the site from being embedded by other pages.
Solution:
Modify the web server configuration and add the X-Frame-Options response header. There are three kinds of assignments:
1. DENY: cannot be embedded in any iframe or frame.
2. SAMEORIGIN: the page can only be embedded in iframe or frame by the page of this site.
3. ALLOW-FROM uri: can only be embedded in the framework of the specified domain name
X-Content-Type-Options:nosniff
If the server sends the response header "X-Content-Type-Options: nosniff", the script and styleSheet elements reject the response containing the wrong MIME type. This is a security feature that helps prevent attacks based on MIME type obfuscation.
Simply understand: by setting the "X-Content-Type-Options: nosniff" response header, script and styleSheet are executed through the MIME type to filter out unsafe files
This change affects the behavior of the browser when the server sends a response with the "X-Content-Type-Options: nosniff" header.
Referrer-Policy:no-referrer
Referrer is the header of the HTTP request header, which is used to indicate the source of the current traffic. Through this information, we can know how visitors come to the current page. This is very important for Web Analytics and can be used to analyze traffic distribution in different channels, keywords searched by users, and so on.
However, this field can also cause disclosure of user sensitive information (such as reset password URL with sensitive information, which is in danger of being reset if collected by Web Analytics).
Referrer Policy States
The new Referrer prescribes five strategies:
No Referrer: do not send Referrer messages under any circumstances
No Referrer When Downgrade: Referrer information is not sent only when the protocol is degraded (such as the introduction of HTTP resources into HTTPS pages). Is the default policy for most browsers.
Origin Only: send a referrer that contains only the host portion.
Origin When Cross-origin: send a Referer containing only host when cross-domain access occurs. It is still intact in the same domain. The difference with Origin Only is to judge whether it is Cross-origin or not. The browser considers it to be the same domain only if the protocol, domain name and port are all the same.
Unsafe URL: all send Referrer messages. The loosest and most insecure policy.
The core idea of Content-Security-Policy:default-src 'self' https:; font-src' self' https: data:; img-src 'self' https: data:; object-src' none'; script-src https:; style-src 'self' https:' unsafe-inline' content Security Policy (CSP) is very simple: a website sends a CSP header to tell browsers what is authorized and what needs to be prohibited. It is known as an artifact specially created to solve XSS attacks. Refer to https://blog.csdn.net/u014465934/article/details/84199171 for more information.
X-Download-Options:noopen
Used to place directly open the user download file.
X-Download-Options: noopen
Noopen is used to specify that users of IE 8 and above save the file without opening it. The Open option is not displayed in the download dialog box.
X-Permitted-Cross-Domain-Policies:none
Used to specify an alternative policy when the "crossdomain.xml" file (the policy file used to make the necessary settings when you need to read Flash content from a file in another domain name) cannot be placed in the root directory of the site, and so on.
X-Permitted-Cross-Domain-Policies: master-only
Master-only only allows the use of master policy files (/ crossdomain.xml)
If you want to modify these Header values, you can use the following configuration:
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-StripPrefix=1 filter: secure-headers : xss-protection-header: 1 Mode=block
The suffix corresponding to the above header:
Xss-protection-header
Strict-transport-security
Frame-options
Content-type-options
Referrer-policy
Content-security-policy
Download-options
Permitted-cross-domain-policies
If you want to disable some Header, you can use the following configuration: spring.cloud.gateway.filter.secure-headers.disable, multiple, separated. For example:
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-StripPrefix=1 filter: secure-headers: disable: frame-options Download-options
SetPath
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match jump by / user-center-Path=/user-center/ {segment} filters: # use / {segment} instead of / user-center/ {segment} and forward-SetPath=/ {segment}
The intention is about the same as before.
SetResponseHeader
There is such a Controller method in the User project
@ GetMapping ("/ addhead") public String addHeader (HttpServletRequest request, HttpServletResponse response) {response.addHeader ("X-Response-Foo", "Foo"); return "header" } spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-StripPrefix=1# will respond to the header X-Response-Foo Change the value of to dee-SetResponseHeader=X-Response-Foo Dee
SetStatus
Modify the status code of the response. The value can be either a number or a string. But it must be a value in the Spring HttpStatus enumeration class.
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-StripPrefix=1# modifies the return status code as 401-SetStatus=401
The result can be returned normally here, but the status code is changed to 401.
StripPrefix
The number indicates the number of paths to truncate.
Retry
To retry for different responses, you can configure the following parameters:
Retries: number of retries
Statuses: the status code that needs to be retried. The value is in org.springframework.http.HttpStatus.
Methods: the request method that needs to be retried. The value is in org.springframework.http.HttpMethod.
Series: HTTP status code series, the value is in org.springframework.http.HttpStatus.Series
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-StripPrefix=1# if the method is not found Retry 3 times-name: Retry args: retries: 3statuses: NOT_FOUND
RequestSize
Sets the maximum request packet size received for the back-end service. If the request size exceeds the set value, 413 Payload Too Large is returned. The default value is 5m
But here I set 1 byte, which doesn't seem to work.
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-StripPrefix=1# if the request packet exceeds 1 byte Return 413-name: RequestSize args: maxSize: 1
Invalid after test
Modify Request Body
It can be used to modify the content of the request body before Gateway sends the request to the back-end microservice. The filter factory is currently in the BETA state and is not recommended.
Modify Response Body
Can be used to modify the content of the response body. The filter factory is currently in the BETA state and is not recommended.
Default
Use this attribute if you want to add filters to all routes.
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/** # this configuration is valid for all routes.id default-filters: # omit the first wildcard after the jump-StripPrefix=1
Custom filter factory
Filter life cycle
Pre: before Gateway forwards the request
Post: after Gateway forwards the request
Customize the way the filter factory
Inheritance: AbstractGatewayFilterFactory
Inheritance: AbstractNameValueGatewayFilterFactory
Core API
Exchange.getRequest (). Mutate (). Xxx / / modify request
Exchange.mutate () .xxx / / modify exchange
Chain.filter (exchange) / / passed to the next filter for processing
Exchange.getResponse / / get the response
Write a filter factory
Now let's write a filter factory that prints logs, and the custom filter factory must end with GatewayFilterFactory
@ Slf4j@Componentpublic class PreLogGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {@ Override public GatewayFilter apply (NameValueConfig config) {return (exchange, chain)-> {log.info ("request came in. {}, {}", config.getName (), config.getValue ()); / / get request ServerHttpRequest modifiedRequest = exchange.getRequest () .mutate () .build () / / get exchange ServerWebExchange modifiedExchange = exchange.mutate () .request (modifiedRequest) .build (); / / pass it to the next filter return chain.filter (modifiedExchange);});}}
Configuration file
Spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848gateway: routes:-id: gateuri: lb://userpredicates: # match the jump by / user-center-Path=/user-center/**filters: # omit the first wildcard after the jump-StripPrefix=1# print a journal b-PreLog=a,b
After running, after we access the API through the gateway, the log is printed as follows
2019-12-20 14 c.c.c.m.g.c.PreLogGatewayFilterFactory 09 INFO 48.066 INFO 2702-[ctor-http-nio-2] c.c.c.m.g.c.PreLogGatewayFilterFactory: request to come in.
Global filter
1 Combined Global Filter and GatewayFilter Ordering
2 Forward Routing Filter
3 LoadBalancerClient Filter
4 Netty Routing Filter
5 Netty Write Response Filter
6 RouteToRequestUrl Filter
7 Websocket Routing Filter
8 Gateway Metrics Filter
9 Marking An Exchange As Routed
Global Filter and GatewayFilter Ordering
When the request arrives, the Filtering Web Handler processor adds all GlobalFilter instances and matching GatewayFilter instances to the filter chain.
The filter chain is sorted in the order specified by the org.springframework.core.Ordered annotation. Spring Cloud Gateway distinguishes between the "pre" and "post" phases of filter logic execution, so the high priority filter will be executed first in the pre phase, and the lowest priority filter will be executed at the end of the post phase. The smaller the number, the more forward the execution.
@ Slf4j@Configurationpublic class GlobleFilters {@ Bean @ Order (- 1) public GlobalFilter a () {return ((exchange, chain)-> {log.info ("first pre filter"); return chain.filter (exchange) .then (Mono.fromRunnable (()-> log.info ("third post filter");}) @ Bean @ Order (0) public GlobalFilter b () {return ((exchange, chain)-> {log.info ("second pre filter"); return chain.filter (exchange) .then (Mono.fromRunnable (()-> log.info ("second post filter");}) } @ Bean @ Order (1) public GlobalFilter c () {return ((exchange, chain)-> {log.info ("third pre filter"); return chain.filter (exchange) .then (Mono.fromRunnable (()-> log.info ("first post filter");});})
When a gateway forwards a request
2019-12-20 15 c.c.c.m.gateway.config.GlobleFilters 03purl 34.263 INFO 3380-[ctor-http-nio-2] c.c.c.m.gateway.config.GlobleFilters: first pre filter
2019-12-20 15 c.c.c.m.gateway.config.GlobleFilters 03purl 34.263 INFO 3380-[ctor-http-nio-2] c.c.c.m.gateway.config.GlobleFilters: second pre filter
2019-12-20 15 c.c.c.m.gateway.config.GlobleFilters 03purl 34.263 INFO 3380-[ctor-http-nio-2] c.c.c.m.gateway.config.GlobleFilters: third pre filter
2019-12-20 15 c.c.c.m.gateway.config.GlobleFilters 03purl 34.302 INFO 3380-[ctor-http-nio-7] c.c.c.m.gateway.config.GlobleFilters: first post filter
2019-12-20 15 c.c.c.m.gateway.config.GlobleFilters 03purl 34.302 INFO 3380-[ctor-http-nio-7] c.c.c.m.gateway.config.GlobleFilters: second post filter
2019-12-20 15 c.c.c.m.gateway.config.GlobleFilters 03purl 34.302 INFO 3380-[ctor-http-nio-7] c.c.c.m.gateway.config.GlobleFilters: third post filter
Forward Routing Filter
Integrate Sentinel to limit current
The version of Sentinel must be 1.6 or above, which is 1.7 in our case
Pom
Com.alibaba.csp sentinel-spring-cloud-gateway-adapter
Add configuration class
Configurationpublic class GatewayConfig {private final List viewResolvers; private final ServerCodecConfigurer serverCodecConfigurer; public GatewayConfig (ObjectProvider viewResolverProvider, ServerCodecConfigurer serverCodecConfigurer) {this.viewResolvers = viewResolverProvider.getIfAvailable (Collections::emptyList); this.serverCodecConfigurer = serverCodecConfigurer;} @ Bean @ Order (Ordered.HIGHEST_PRECEDENCE) public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler () {return new SentinelGatewayBlockExceptionHandler (viewResolvers,serverCodecConfigurer);} @ Bean @ Order (Ordered.HIGHEST_PRECEDENCE) public GlobalFilter sentinelGatewayFilter () {return new SentinelGatewayFilter () } @ PostConstruct public void doInit () {initGatewayRules ();} / * configure current limit rules * / private void initGatewayRules () {Set rules = new HashSet (); rules.add (new GatewayFlowRule ("gate") .setCount (1) / / current limit threshold .setIntervalSec (1)) / / Statistical time window (in seconds). Default is 1 second GatewayRuleManager.loadRules (rules);}}
We can only pass one request for 1 second.
If we request two or more times in 1 second, a current limit prompt will be generated.
Gateway cross-domain settings
Import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.reactive.CorsWebFilter;import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;import org.springframework.web.util.pattern.PathPatternParser;/** * Cross-domain configuration * / @ Configurationpublic class CrossDomainConfig {@ Bean public CorsWebFilter corsFilter () {CorsConfiguration config = new CorsConfiguration (); config.addAllowedMethod ("*") Config.addAllowedOrigin ("*"); config.addAllowedHeader ("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource (new PathPatternParser ()); source.registerCorsConfiguration ("/ *", config); return new CorsWebFilter (source);}}
Or profile configuration
Spring: application: name: gateway cloud: nacos: discovery: server-addr: xxx.xxx.xxx.xxx:8848gateway: discovery: locator: true # Cross-domain globalcors: corsConfigurations:'[/ *]': allowedHeaders: "*" allowedOrigins: "*" allowedMethods: -is it helpful for GET POST DELETE PUT OPTION to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.