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

使用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 自己写一个


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

特此记录! 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值