您的位置:首页 > 理论基础 > 计算机网络

使用HttpClient 访问Spring OAuth 2.0接口 获取token

2018-01-02 20:36 1086 查看
使用Sring Security的 Oauth2.0 搭建还是很轻松的

不过一旦遇到问题. 花费的时间可能会比你自己实现 还要浪费时间

前几天遇到的坑是 居然无法使用 ajax 跨域进行获取 /oauth/token 

具体原因就是跨域时发送的 OPTIONS 请求无论怎样都是401 

其实这一层预访问. 可以忽略安全验证的, 

我遇到的问题和这个老兄 几乎一致
https://segmentfault.com/q/1010000005944442
使用了这个老兄的方法
http://www.imooc.com/article/7719
发现在spring-boot中 自定义的filter 自会在security加载后才会起作用

后来使用了继承了 GenericFilterBean 的方法 然后在Resource Server Config 加入过滤器链.  

http.addFilterBefore(new BeforeLoginFilter(), UsernamePasswordAuthenticationFilter.class);

发现访问 Oauth/token 时security 会有另外一套过滤器链, 最后还是失败了

感觉有点恶心了, 最后还是使用代理这种不优雅的方式来实现 

也就是使用httpclient 在服务器端实现请求,然后再返回给跨域请求者

吐槽下4.5.3 版本的httpClinet 真难用 语法改动太大了, 以前用这个httpclient 老版本做爬虫的时候用用起来真心舒服

public static String AuthHttpPost(String url) {
RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();

String result = "";
HttpPost httpPost = new HttpPost(url);       // 拼接参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
//list.add(new BasicNameValuePair("grant_type", "password"));
System.out.println("==== 提交参数 ======" + list);
CloseableHttpResponse response = null;
try {
httpPost.setEntity(new UrlEncodedFormEntity(list));
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
System.out.println("========HttpResponseProxy:========" + statusCode);
HttpEntity entity = response.getEntity();

if (entity != null) {
result = EntityUtils.toString(entity, "UTF-8");
System.out.println("========接口返回=======" + result);
}
EntityUtils.consume(entity);

} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}


还要吐槽 CSDN 这个编辑器 真不好用

其中测试 摸索的过程 毫无快感, 实现后感觉毫无艺术感! 

以后一定要用node.js 自己写一个

我想大家可能也遇到过此类为题, 百度了很久, 找不到解决 方案 或者干脆文不对题!

特此记录! 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐