背景
因为开发微信公众号需要白名单,挂一个代理在服务器上方面测试,但不加账号密码验证很不安全,会被其他服务器扫描使用,所以要增加账号密码校验。
服务器
采用apache,需要开启vhost模式,使用htpasswd创建账号密码
htpasswd -bc ./conf/password.file user 123456 #创建用(user)户和密码(123456)
<VirtualHost *:8084>
#ServerName proxypass.akoles.com
ProxyRequests On
ProxyVia Block
ErrorLog ${SRVROOT}/conf/log/error.log
CustomLog ${SRVROOT}/conf/log/access.log combined
<Proxy *>
AuthType Basic
AuthName "Restricted Resource"
#密码
AuthUserFile "${SRVROOT}/conf/password.file"
#分组
#AuthGroupFile "${SRVROOT}/conf/group.file"
<RequireAny>
Require all denied
Require group usergroup
</RequireAny>
</Proxy>
</VirtualHost>
应用
java使用5.X版本的hutool,4.X版本应该可以使用
//代理http需要身份验证
public static String sendPostFromProxy(String url, String jsonStr,String cookie) {
// 这行代码是身份验证的关键配置,不然身份验证不起作用
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
String serverProxyIP = Content.serverProxyIP;//代理服务器IP
int serverProxyPort = Content.serverProxyPort;//代理服务器端口
Authenticator.setDefault(new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
//serverProxyUsername 用户名
//serverProxyPassword 密码
return new PasswordAuthentication(serverProxyUsername, serverProxyPassword.toCharArray());
}
});
HttpRequest httpRequest = HttpUtil.createPost(url).body(jsonStr);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(serverProxyIP, serverProxyPort));
httpRequest.setProxy(proxy);
return httpRequest.execute().body();
}