33

服务之间调用还需要鉴权?

 3 years ago
source link: https://mp.weixin.qq.com/s/epnm9uqQTdpkNzmSD5GLhw
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一、背景

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

MNnAZ3E.png!web

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

二、思路

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

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

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

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

三、实现

3.1 自定义注解

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

1@Target(ElementType.METHOD)
2@Retention(RetentionPolicy.RUNTIME)
3@Documented
4public @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    }
16
17    @Override
18    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    @Override
10    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    }
25
26    @Override
27    public void setApplicationContext(ApplicationContext context) {
28        this.applicationContext = context;
29    }
30
31    public List<String> getUrls() {
32        return urls;
33    }
34
35    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@Inner
3public 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 GlobalFilter, Ordered {
 3
 4    @Override
 5    public Mono<Void> filter(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    }
20
21    @Override
22    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}

五、总结

这样我们总共实现了以下几个功能:

  1. 服务间访问可以不鉴权,添加注解@Inner即可。

  2. 网关访问不需要鉴权的资源,添加注解@Inner(value=false)即可。当然,这样服务间不鉴权也可以访问。

  3. 为了安全性考虑,将网关中的请求头form参数清洗,以防有人模拟请求,来访问资源。

由于各个服务都是在内网环境中,只有网关会暴露公网,因此服务间调用是没必要鉴权的。

< END >


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK