問(wèn)題描述
我有一個(gè)微服務(wù)架構(gòu),它們都由 Spring Security 和 JWT 令牌保護(hù).
I have a microservice architecture, both of them securized by spring security an JWT tokens.
因此,當(dāng)我調(diào)用我的第一個(gè)微服務(wù)時(shí),我想獲取 JWT 令牌并使用這些憑據(jù)向另一個(gè)服務(wù)發(fā)送請(qǐng)求.
So, when I call my first microservice, I want to take the JWT token and send a request to another service using those credentials.
如何檢索令牌并再次發(fā)送到其他服務(wù)?
How can I retrieve the token and sent again to the other service?
推薦答案
我已經(jīng)完成了任務(wù),創(chuàng)建了一個(gè)自定義過(guò)濾器
I've accomplished the task, creating a custom Filter
public class RequestFilter implements Filter{
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String token = httpServletRequest.getHeader(RequestContext.REQUEST_HEADER_NAME);
if (token == null || "".equals(token)) {
throw new IllegalArgumentException("Can't retrieve JWT Token");
}
RequestContext.getContext().setToken(token);
chain.doFilter(request, response);
}
@Override
public void destroy() { }
@Override
public void init(FilterConfig arg0) throws ServletException {}
}
然后,在我的配置中設(shè)置
Then, setting in my config
@Bean
public FilterRegistrationBean getPeticionFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new RequestFilter());
registration.addUrlPatterns("/*");
registration.setName("requestFilter");
return registration;
}
考慮到這一點(diǎn),我創(chuàng)建了另一個(gè)具有 ThreadLocal 變量的類(lèi),以將 JWT 令牌從 Controller 傳遞到 Rest Templace 攔截器
With that in mind, I've create another class with a ThreadLocal variable to pass the JWT token from the Controller to the Rest Templace interceptor
public class RequestContext {
public static final String REQUEST_HEADER_NAME = "Authorization";
private static final ThreadLocal<RequestContext> CONTEXT = new ThreadLocal<>();
private String token;
public static RequestContext getContext() {
RequestContext result = CONTEXT.get();
if (result == null) {
result = new RequestContext();
CONTEXT.set(result);
}
return result;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor{
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
String token = RequestContext.getContext().getToken();
request.getHeaders().add(RequestContext.REQUEST_HEADER_NAME, token);
return execution.execute(request, body);
}
}
在配置中添加攔截器
@PostConstruct
public void addInterceptors() {
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
interceptors.add(new RestTemplateInterceptor());
restTemplate.setInterceptors(interceptors);
}
這篇關(guān)于使用 Spring Rest 模板在服務(wù)上傳播 HTTP 標(biāo)頭(JWT 令牌)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!