温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java怎么实现给接口增加一个参数

发布时间:2022-03-24 13:45:23 阅读:931 作者:iii 栏目:大数据
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

这篇“java怎么实现给接口增加一个参数”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“java怎么实现给接口增加一个参数”文章吧。

一、背景

一般在微服务架构中我们都会使用spring security oauth3来进行权限控制,我们将资源服务全部放在内网环境中,将API网关暴露在公网上,公网如果想要访问我们的资源必须经过API网关进行鉴权,鉴权通过后再访问我们的资源服务。我们根据如下图片来分析一下问题。

java怎么实现给接口增加一个参数

现在我们有三个服务:分别是用户服务、订单服务和产品服务。用户如果购买产品,则需要调用产品服务生成订单,那么我们在这个调用过程中有必要鉴权吗?答案是否定的,因为这些资源服务放在内网环境中,完全不用考虑安全问题。 

二、思路

如果要想实现这个功能,我们则需要来区分这两种请求,来自网关的请求进行鉴权,而服务间的请求则直接调用。

是否可以给接口增加一个参数来标记它是服务间调用的请求?

这样虽然可以实现两种请求的区分,但是实际中不会这么做。一般情况下服务间调用和网关请求的数据接口是同一个接口,如果写成两个接口来分别给两种请求调用,这样无疑增加了大量重复代码。也就是说我们一般不会通过改变请求参数的个数来实现这两种服务的区分。

虽然不能增加请求的参数个数来区分,但是我们可以给请求的header中添加一个参数用来区分。这样完全可以避免上面提到的问题。 

三、实现 

3.1 自定义注解

我们自定义一个Inner的注解,然后利用aop对这个注解进行处理

1@Target(ElementType.METHOD)2@Retention(RetentionPolicy.RUNTIME)3@Documented4public @interface Inner {5    /**6     * 是否AOP统一处理7     */8    boolean value() default true;9
 1@Aspect 2@Component 3public class InnerAspect implements Ordered { 4 5    private final Logger log = LoggerFactory.getLogger(InnerAspect.class); 6 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("访问接口 {} 没有权限", point.getSignature().getName());12            throw new AccessDeniedException("Access is denied");13        }14        return point.proceed();15    }1617    @Override18    public int getOrder() {19        return Ordered.HIGHEST_PRECEDENCE + 1;20    }21

上面这段代码就是获取所有加了@Inner注解的方法或类,判断请求头中是否有我们规定的参数,如果没有,则不允许访问接口。 

3.2 暴露url

将所有注解了@Inner的方法和类暴露出来,允许不鉴权可以方法,这里需要注意的点是如果方法使用pathVariable 传参的,则需要将这个参数转换为*。如果不转换,当成接口的访问路径,则找不到此接口。

 1@Configuration 2public class PermitAllUrlProperties implements InitializingBean, ApplicationContextAware{ 3 4    private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}"); 5    private ApplicationContext applicationContext; 6    private List<String> urls = new ArrayList<>(); 7    public static final String ASTERISK = "*"; 8 9    @Override10    public void afterPropertiesSet() {11        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);12        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();13        map.keySet().forEach(info -> {14            HandlerMethod handlerMethod = map.get(info);15            // 获取方法上边的注解 替代path variable 为 *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            // 获取类上边的注解, 替代path variable 为 *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    }2526    @Override27    public void setApplicationContext(ApplicationContext context) {28        this.applicationContext = context;29    }3031    public List<String> getUrls() {32        return urls;33    }3435    public void setUrls(List<String> urls) {36        this.urls = urls;37    }38} 

在资源服务器中,将请求暴露出来

 1public void configure(HttpSecurity httpSecurity) throws Exception { 2    //允许使用iframe 嵌套,避免swagger-ui 不被加载的问题 3    httpSecurity.headers().frameOptions().disable(); 4    ExpressionUrlAuthorizationConfigurer<HttpSecurity> 5        .ExpressionInterceptUrlRegistry registry = httpSecurity 6        .authorizeRequests(); 7    // 将上面获取到的请求,暴露出来 8    permitAllUrl.getUrls() 9        .forEach(url -> registry.antMatchers(url).permitAll());10    registry.anyRequest().authenticated()11        .and().csrf().disable();12}  
  

3.3 如何去请求

定义一个接口:

1@PostMapping("test")2@Inner3public String test(@RequestParam String id){4    return id;5

定义feign远程调用接口

1@PostMapping("test")2MediaFodderBean test(@RequestParam("id") String id,@RequestHeader(SecurityConstants.FROM) String from);

服务间进行调用,传请求头

1 String id = testService.test(id, SecurityConstants.FROM_IN);  

四、思考 

4.1 安全性

上面虽然实现了服务间调用,但是我们将@Inner的请求暴露出去了,也就是说不用鉴权既可以访问到,那么我们是不是可以模拟一个请求头,然后在其他地方通过网关来调用呢?

答案是可以,那么,这时候我们就需要对网关中分发的请求进行处理,在网关中写一个全局拦截器,将请求头的form参数清洗。

 1@Component 2public class RequestGlobalFilter implements GlobalFilterOrdered { 3 4    @Override 5    public Mono<Voidfilter(ServerWebExchange exchange, GatewayFilterChain chain) { 6        // 清洗请求头中from 参数 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    }2021    @Override22    public int getOrder() {23        return -1000;24    }25}  
  

4.2 扩展性

我们自定义@Inner注解的时候,放了一个boolean类型的value(),默认为true。如果我们想让这个请求可以通过网关访问的话,将value赋值为false即可。

1@PostMapping("test")2@Inner(value=false)3public String test(@RequestParam String id){4    return id;5}

以上就是关于“java怎么实现给接口增加一个参数”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

原文链接:https://my.oschina.net/u/4021330/blog/4412135

AI

开发者交流群×