使用 spring-session 在微服务之间传播凭据的最佳方法 [英] Best way to propagate credentials between micro services using spring-session

查看:44
本文介绍了使用 spring-session 在微服务之间传播凭据的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用的架构与 关于 spring.io 的这篇很棒的指南.我们的网关处理身份验证,会话使用 spring-session 存储在 Redis 中.我们微服务的端点是安全的,并且也使用 spring-session.

We are using an architecture very similar to the one described in this great guide on spring.io. Our gateway handles authentication, and sessions are stored in Redis using spring-session. Endpoints of our micro services are secured and also use spring-session.

在微服务中,我需要调用另一个微服务的端点.我可以通过发现客户端轻松获取 URL,但我需要提供凭据,但我不确定实现该目标的最佳方法.

In a micro service I need to call an endpoint of another micro service. I get the URL easily through the discovery client, but I need to provide credentials and I'm not sure of the best way to achieve that.

我正在考虑从 HttpRequest 中获取 SESSION cookie,将其存储在某种线程局部变量或请求作用域 bean 中,并在 RestTemplate 中使用它来调用第二个微服务.我需要这个请求范围的 bean,因为 RestTemplate 将用于服务层,即不在 MVC 控制器中,而且我不想用我从 cookie 中获得的这个会话标识符污染我的服务层方法.

I am thinking about getting the SESSION cookie from the HttpRequest, store it in some kind of thread local variables or request scope bean, and use it in the RestTemplate to call the second micro service. I need this request scoped bean because the RestTemplate will be used in the service layer, i.e. not in the MVC controller, and I don't want to pollute my service layer methods with this session identifier I get from the cookie.

有没有更好的方法来满足这种需求?Spring Cloud 中是否已经对此提供了一些支持?

Is there a better way to approach this need? Is there already some support in Spring Cloud for this?

非常感谢您的意见

推荐答案

此时访问 Spring Session id 的最简单方法是使用 RequestContextHolder.getRequestAttributes().getId().获得访问权限后,您可以编写自定义 ClientHttpRequestInterceptor 以在请求中包含会话 ID:

At this time the easiest way to access the Spring Session id is using RequestContextHolder.getRequestAttributes().getId(). Once you have access to that you can write a custom ClientHttpRequestInterceptor to include the session id in requests:

public SpringSessionClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException {
        boolean isMyService = ...;

        // very important not to send the session id to external services
        if(isMyService) {
            request.getHeaders().add("x-auth-token", RequestContextHolder.getRequestAttributes().getId());
        }
    }
}

然后在创建 RestTemplate 时确保添加 SpringSessionClientHttpRequestInterceptor.

Then when you create your RestTemplate make sure to add SpringSessionClientHttpRequestInterceptor.

RestTemplate rest = new RestTemplate();
rest.getInterceptors().add(new SpringSessionClientHttpRequestInterceptor());

这篇关于使用 spring-session 在微服务之间传播凭据的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆