关于Spring RestTemplate使用ClientHttpRequestInterceptor配置http请求header
2019-07-02 16:56
507 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_36723134/article/details/94446386
当我们在springboot中跨微服务请求时候,有时候需要Authentication的验证,这个时候可能需要在请求头中设置相应的token, 所以Spring提供了相应的拦截器以供我们配置。
-
创建一个拦截器:
public ClientHttpRequestInterceptor restTemplateInterceptor(){ return new ClientHttpRequestInterceptor(){ @Override public ClientHttpResponse interceptor(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) Throws IOException{ // 通过请求获取请求中的header参数 HttpHeaders headers = request.getHeaders(); // 往header中设置自己需要的参数 headers.add("Authorization", getAuthorization()); headers.add("Content-Type", "application/json"); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); } } }
-
// 获取token, authorization
private String getAuthorization(){ Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String jwt = tokenProvider.createToken(auth, false); return "Bearer " + jwt; }
-
//上面的tokenProvider是注入的,是通过Jhipster生成的类
@Autowired private TokenProvider tokenProvider;
- // 最后一步获取我们需要的RestTemplate
@Bean @LoadBalanced public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setInterceptors(Collections.singletonList(restInterceptor())); return restTemplate; }
利用restTemplate用admin固定用户名模拟登录:
-
首先新建一个类并继承RestTemplate:
public class RestTemplateEnd extends RestTemplate { }
-
新建一个RestTemplateEndConfig类:
@Configuration public class RestTemplateEndConfig{ @Bean @LoadBalanced public RestTemplateEnd endRest() { RestTemplateEnd rest = new RestTemplateEnd (); rest.setInterceptors(Collections.singletonList(endRestInterceptor())); return rest; } private ClientHttpRequestInterceptor endRestInterceptor() { return new ClientHttpRequestInterceptor() { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { HttpHeaders headers = request.getHeaders(); setHeaders(headers, resetEndAuthorization()); return execution.execute(request, body); } }; } private String resetEndAuthorization() { if(StringUtils.isEmpty(authentication) || !tokenProvider.validateToken(authentication)) { Map<String, String> map = new HashMap<>(); map.put("username", this.username); map.put("password", this.password); HttpHeaders headers = new HttpHeaders(); headers.setContentType(new MediaType("application", "json", StandardCharsets.UTF_8)); headers.add("Authorization", ""); HttpEntity<Map<String, String>> entity = new HttpEntity<>(map, headers); String url = "https://xxxx"+contextPath+"/api/authenticate"; RestTemplate restTemplate = restTemplate(); restTemplate.setRequestFactory(new SkipSslVerificationHttpRequestFactory()); @SuppressWarnings("rawtypes") ResponseEntity<Map> token = restTemplate().exchange(url, HttpMethod.POST, entity, Map.class); authentication = token.getBody().get("id_token").toString(); } return "Bearer " + authentication; } private void setHeaders(HttpHeaders headers, String token) { headers.add("Authorization", token); headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); } }
类SkipSslVerificationHttpRequestFactory
import java.io.IOException; import java.net.HttpURLConnection; import java.security.SecureRandom; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.springframework.http.client.SimpleClientHttpRequestFactory; /** * {@link SimpleClientHttpRequestFactory} that skips SSL certificate verification. * * @author Madhura Bhave */ public class SkipSslVerificationHttpRequestFactory extends SimpleClientHttpRequestFactory { @Override protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { if (connection instanceof HttpsURLConnection) { prepareHttpsConnection((HttpsURLConnection) connection); } super.prepareConnection(connection, httpMethod); } private void prepareHttpsConnection(HttpsURLConnection connection) { connection.setHostnameVerifier(new SkipHostnameVerifier()); try { connection.setSSLSocketFactory(createSslSocketFactory()); } catch (Exception ex) { // Ignore } } private SSLSocketFactory createSslSocketFactory() throws Exception { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] { new SkipX509TrustManager() }, new SecureRandom()); return context.getSocketFactory(); } private class SkipHostnameVerifier implements HostnameVerifier { @Override public boolean verify(String s, SSLSession sslSession) { return true; } } private static class SkipX509TrustManager implements X509TrustManager { @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) { } } }
相关文章推荐
- Spring boot 发送http请求组件RestTemplate使用实例
- 【web】Spring RestTemplate提交时设置http header请求头
- 解决spring3.0.5使用RestTemplate发送post请求响应中文乱码问题
- Springmvc RestTemplate 使用 && json xml rest 配置
- 使用 Spring 3 MVC HttpMessageConverter 功能构建 RESTful web 服务(包括使用 RestTemplate 与 REST 服务进行通信)
- java后端发送http请求使用RestTemplate(简单的都无敌了)
- 如何使用火狐下的两款接口测试工具RESTClient和HttpRequester发送post请求
- Java后端用HttpClient和RestTemplate发送请求实例
- 关于HttpClient在服务器端使用请求碰到的问题总结
- HttpHeader,restTemplate.postForObject()使用
- 使用FireFox插件RESTClient、HttpRequester模拟http(get post)请求
- HttpClient与Spring RestTemplate
- How to Send an HTTP Header With Every Request With Spring RestTemplate
- spring restTemplate 携带参数和header头信息,发送post请求
- springboot restTemplate使用以及相关配置
- 如何使用火狐下的两款接口测试工具RESTClient和HttpRequester发送post请求
- http请求使用 RestTemplate 发送 post 请求传递参数
- spring boot RestTemplate 发送 get 请求使用误区
- 反射:修改请求头HttpWebRequest/Webclient Header属性的date值-"此标头必须使用适当的属性进行修改"
- Spring RestTemplate与apache HttpClient