使用Spring rest模板

时间:2017-10-13 11:45:10

标签: java spring rest jwt

我有一个微服务架构,它们都由弹簧安全和JWT令牌证明。

因此,当我调用我的第一个微服务时,我想使用JWT令牌并使用这些凭据向另一个服务发送请求。

如何检索令牌并再次发送给其他服务?

3 个答案:

答案 0 :(得分:7)

基本上,您的令牌应位于请求的标头中,例如:授权:承载。要获得它,您可以通过控制器中的@RequestHeader()检索任何标头值:

@GetMapping("/someMapping")
public String someMethod(@RequestHeader("Authorization") String token) {

}

现在,您可以将令牌放在标题中,以便执行以下请求:

HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", token);

HttpEntity<RestRequest> entityReq = new HttpEntity<RestRequest>(request, headers);

现在您可以将HttpEntity传递给您的其余模板:

template.exchange("RestSvcUrl", HttpMethod.POST, entityReq, SomeResponse.class);

希望我能帮忙

答案 1 :(得分:5)

我已完成任务,创建自定义过滤器

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 {}


}

然后,在我的配置中设置

    @Bean
public FilterRegistrationBean getPeticionFilter() {

    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(new RequestFilter());
    registration.addUrlPatterns("/*");
    registration.setName("requestFilter");

    return registration;
}

考虑到这一点,我创建了另一个带有ThreadLocal变量的类,以将JWT令牌从Controller传递给Rest Templace拦截器

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);
}

答案 2 :(得分:0)

我认为最好将拦截器专门添加到RestTemplate中,如下所示:

const fetchData = {
  requested() {
    return {
      type: FETCH_DATA.REQUESTED
    };
  },
}

像这样将其添加到RestTemplate中:

const fetchData = {
  {REQUESTED}: FETCH_DATA,
  requested() {
    return {
      type: REQUESTED
    }
  }
}

这样,每次您需要RestTemplate时,都可以使用自动装配来获取它。您仍然需要实现AuthenticationService才能从TokenStore中获取令牌,如下所示:

class RestTemplateHeaderModifierInterceptor(private val authenticationService: IAuthenticationService) : ClientHttpRequestInterceptor {
    override fun intercept(request: org.springframework.http.HttpRequest, body: ByteArray, execution: ClientHttpRequestExecution): ClientHttpResponse {
        if (!request.headers.containsKey("Authorization")) {
            // don't overwrite, just add if not there.
            val jwt = authenticationService.getCurrentUser()!!.jwt
            request.headers.add("Authorization", "Bearer $jwt")
        }
        val response = execution.execute(request, body)
        return response
    }
}