In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
The knowledge of this article "how to add a parameter to the interface by java" is not quite understood by most people, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to add a parameter to the interface by java" article.
I. background
Generally speaking, in the micro-service architecture, we use spring security oauth3 for permission control. We put all the resource services in the private network environment and expose the API gateway on the public network. If the public network wants to access our resources, it must be authenticated through the API gateway, and then access our resource services after authentication. Let's analyze the problem according to the picture below.
Now we have three services: user service, order service and product service. If a user buys a product, he or she needs to call the product service to generate an order, so is it necessary for us to authenticate during this call? The answer is no, because these resource services are placed in an intranet environment and do not have to consider security issues at all.
Second, train of thought
If we want to implement this function, we need to distinguish between the two kinds of requests, the requests from the gateway are authenticated, and the requests between services are called directly.
Can you add a parameter to the interface to mark it as a request for inter-service invocation?
This makes it possible to distinguish between the two requests, but it will not be done in practice. In general, the data interface of the inter-service call and the gateway request is the same interface, if it is written as two interfaces to call the two requests respectively, this will undoubtedly add a lot of duplicate code. In other words, we generally do not distinguish between the two services by changing the number of request parameters.
Although it is not possible to increase the number of parameters requested to distinguish, we can add a parameter to the requested header to distinguish. This can completely avoid the problems mentioned above.
Third, implement 3.1 custom annotations
We customize an annotation for Inner, and then use aop to process it
1@Target (ElementType.METHOD)
2@Retention (RetentionPolicy.RUNTIME)
3@Documented
4public @ interface Inner {
5 / *
6 * whether it is handled by AOP
7 * /
8 boolean value () default true
9} 1@Aspect
2@Component
3public class InnerAspect implements Ordered {
four
5 private final Logger log = LoggerFactory.getLogger (InnerAspect.class)
six
7 @ Around ("@ annotation (inner)")
8 public Object around (ProceedingJoinPoint point, Inner inner) throws Throwable {
9 String header = ServletUtils.getRequest () .getHeader (SecurityConstants.FROM)
10 if (inner.value () & &! StringUtils.equals (SecurityConstants.FROM_IN, header)) {
11 log.warn ("access interface {} does not have permission", point.getSignature () .getName ())
12 throw new AccessDeniedException ("Access is denied")
13}
14 return point.proceed ()
15}
sixteen
17 @ Override
18 public int getOrder () {
19 return Ordered.HIGHEST_PRECEDENCE + 1
20}
21}
The above code is to get all the methods or classes annotated with @ Inner to determine whether there are any parameters in the request header. If not, access to the interface is not allowed.
3.2 exposure to url
Expose all methods and classes annotated with @ Inner, and allow methods without authentication. It is important to note that if the method uses pathVariable to pass parameters, you need to convert this parameter to *. If the interface is not converted as the access path of the interface, the interface cannot be found.
1@Configuration
2public class PermitAllUrlProperties implements InitializingBean, ApplicationContextAware {
three
4 private static final Pattern PATTERN = Pattern.compile ("\ (. *?)\\}")
5 private ApplicationContext applicationContext
6 private List urls = new ArrayList ()
7 public static final String ASTERISK = "*"
eight
9 @ Override
10 public void afterPropertiesSet () {
11 RequestMappingHandlerMapping mapping = applicationContext.getBean (RequestMappingHandlerMapping.class)
12 Map map = mapping.getHandlerMethods ()
13 map.keySet () .forEach (info-> {
14 HandlerMethod handlerMethod = map.get (info)
15 / / the annotations above the get method replace path variable as *
16 Inner method = AnnotationUtils.findAnnotation (handlerMethod.getMethod (), Inner.class)
17 Optional.ofNullable (method) .ifPresent (inner-> info.getPatternsCondition () .getPatterns ()
18. ForEach (url-> urls.add (ReUtil.replaceAll (url, PATTERN, ASTERISK)
19 / / get the comments above the class, and replace path variable with *
20 Inner controller = AnnotationUtils.findAnnotation (handlerMethod.getBeanType (), Inner.class)
21 Optional.ofNullable (controller) .ifPresent (inner-> info.getPatternsCondition () .getPatterns ()
22. ForEach (url-> urls.add (ReUtil.replaceAll (url, PATTERN, ASTERISK)
23})
24}
twenty-five
26 @ Override
27 public void setApplicationContext (ApplicationContext context) {
28 this.applicationContext = context
29}
thirty
31 public List getUrls () {
32 return urls
33}
thirty-four
35 public void setUrls (List urls) {
36 this.urls = urls
37}
38}
Expose the request in the resource server
1public void configure (HttpSecurity httpSecurity) throws Exception {
2 / / allow iframe nesting to avoid the problem that swagger-ui is not loaded
3 httpSecurity.headers () .frameOptions () .disable ()
4 ExpressionUrlAuthorizationConfigurer
5. ExpressionInterceptUrlRegistry registry = httpSecurity
6. AuthorizeRequests ()
7 / / expose the request obtained above
8 permitAllUrl.getUrls ()
9. ForEach (url-> registry.antMatchers (url) .permitAll ())
10 registry.anyRequest () .authenticated ()
11. And () .csrf () .disable ()
12} 3.3 how to request
Define an interface:
1@PostMapping ("test")
2@Inner
3public String test (@ RequestParam String id) {
4 return id
5}
Define feign remote invocation interface
1@PostMapping ("test")
2MediaFodderBean test (@ RequestParam ("id") String id,@RequestHeader (SecurityConstants.FROM) String from)
Call between services and send a request to the head
1 String id = testService.test (id, SecurityConstants.FROM_IN); 4. Think about security
Although we have implemented the inter-service call above, we have exposed the request for @ Inner, that is, it can be accessed without authentication, so can we simulate a request header and call it through the gateway somewhere else?
The answer is yes, so at this point we need to process the request distributed in the gateway, write a global interceptor in the gateway and clean the form parameter of the request header.
1@Component
2public class RequestGlobalFilter implements GlobalFilter, Ordered {
three
4 @ Override
5 public Mono filter (ServerWebExchange exchange, GatewayFilterChain chain) {
6 / / from parameters in the cleaning request header
7 ServerHttpRequest request = exchange.getRequest () .mutate ()
8. Headers (httpHeaders-> httpHeaders.remove (SecurityConstants.FROM))
9. Build ()
10 addOriginalRequestUrl (exchange, request.getURI ())
11 String rawPath = request.getURI () .getRawPath ()
12 ServerHttpRequest newRequest = request.mutate ()
13. Path (rawPath)
14. Build ()
15 exchange.getAttributes () .put (GATEWAY_REQUEST_URL_ATTR, newRequest.getURI ()
16 return chain.filter (exchange.mutate ()
17. Request (newRequest.mutate ())
18. Build (). Build ()
19}
twenty
21 @ Override
22 public int getOrder () {
23 return-1000
24}
25} 4.2 scalability
When we customize the @ Inner annotation, we put a value () of type boolean, which defaults to true. If we want this request to be accessible through the gateway, just assign value to false.
1@PostMapping ("test")
2@Inner (value=false)
3public String test (@ RequestParam String id) {
4 return id
5} the above is the content of this article on "how to add a parameter to the interface by java". I believe everyone has a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to learn more about the relevant knowledge, please follow the industry information channel.
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.