1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class RealmProtectedResourceProvider {
private static final String REALM_FORM_NAME = "j_security_check";
private URL baseUrl = null;
private String tomcatContext = null;
private String loginUrl = null;
private String logoutUrl = null;
private String dummyUrl = null;
private String jSessionId = null;
/**
* Build a new provider
*
* @param baseUrl : the web base url "http://www.example.com:8080"
* @param tomcatContext : might be "/web"
* @param loginUrl : if not null, this page will be called after form authentication
* @param logoutUrl : if not null, this page will be called at the end of getContent() process
* @param dummyUrl : mandatory - usually be index page of context but could be any valid page
* @throws Exception
*/
public RealmProtectedResourceProvider(URL baseUrl, String tomcatContext, String loginUrl, String logoutUrl, String dummyUrl) throws Exception {
// controls
if (baseUrl == null)
throw new Exception("Please, provide a valid base URL !");
if (tomcatContext == null)
throw new Exception("Please, provide a valid tomcat context");
if (dummyUrl == null)
throw new Exception("Please, provide a valid url for authentication process");
// be sure of url format
if (!tomcatContext.startsWith("/"))
tomcatContext = "/" + tomcatContext;
if (tomcatContext.endsWith("/"))
tomcatContext = tomcatContext.substring(0, tomcatContext.length() - 2);
if (!dummyUrl.startsWith("/"))
dummyUrl = "/" + dummyUrl;
// init
this.baseUrl = baseUrl;
this.tomcatContext = tomcatContext;
this.loginUrl = loginUrl;
this.logoutUrl = logoutUrl;
this.dummyUrl = dummyUrl;
}
/**
* Authenticate user by posting a Realm form. Also deal with HTTPS configuration.
*
* @param userName
* @param userPwd
* @throws Exception
*/
public void login(String userName, String userPwd) throws Exception {
String content = null;
// check if we don't have any session
if (jSessionId != null)
return;
// controls
if (userName == null || userPwd == null)
throw new Exception("You must provide a valid login/password to get any protected resource");
// // HTTPS specific code
if (baseUrl.getProtocol().equalsIgnoreCase("https"))
configureHttps();
// try to load the root page of context
URL url = new URL(buildAbsoluteUrl(this.dummyUrl));
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// flush the output
content = flushOutput(connection.getInputStream());
// Is this the login form (find the form's standard action value) ?
if (content != null && content.indexOf(REALM_FORM_NAME) > 0) {
// it's the form, so we can authenticatethe user first
// extract the JSESSIONID from the "Set-Cookie" header
String cookies = connection.getHeaderField("Set-Cookie");
if (cookies == null)
throw new Exception("No cookie get from first URL call in automatic authentication call");
String[] partsCookies = cookies.split(";");
for (String part : partsCookies) {
if (part.contains("JSESSIONID")) {
String[] subparts = part.split("=");
this.jSessionId = subparts[1];
break;
}
}
// check sessionId
if (this.jSessionId == null)
throw new Exception("Automatic authentication : unable to get a valid session Id from cookie");
// then authenticate
authenticateAndRedir(userName, userPwd);
// no need here to deal with redirection
// complete the authentication step by this optional URL call (might be used to init some application session objects)
if (this.loginUrl != null) {
getContent("index.do");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
}
}
/**
* Performs a logout
*
* @throws Exception
*/
public void logout() throws Exception {
if (this.logoutUrl != null)
getContent(this.logoutUrl);
else
throw new Exception("Unable to logout - no url were provided");
}
/**
* Get HTML output of input URL. Performs a Realm authentication if necessary.
*
* @param page
* @return
* @throws Exception
*/
public String getContent(String page) throws Exception {
String content = null;
// check session
if (jSessionId == null)
throw new Exception("Unable to get HTML content of page " + page + " without a valid session - please, call startSession first");
// check page url
if (!page.startsWith("/"))
page = "/" + page;
// try to load the requested page
URL url = new URL(buildAbsoluteUrl(page));
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
// append the session to the headers, so the server may identify us
connection.addRequestProperty("Cookie", "JSESSIONID=" + jSessionId);
connection.connect();
// flush the output
content = flushOutput(connection.getInputStream());
} catch (IOException e) {
throw e;
} finally {
if (connection != null)
connection.disconnect();
}
return content;
}
/**
* POST a form as expected by Realm
*
* @param userName
* @param userPwd
* @throws Exception
*/
private void authenticateAndRedir(String userName, String userPwd) throws Exception {
// Post Realm form
URL url = new URL(buildAbsoluteUrl("/j_security_check"));
HttpURLConnection connection = null;
try {
// open connection
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setUseCaches(false);
// add headers
Map<String, String> h = new LinkedHashMap<String, String>();
h.put("REFERER", buildAbsoluteUrl(""));
h.put("Cookie", "JSESSIONID=" + this.jSessionId);
h.put("Content-Type", "application/x-www-form-urlencoded");
h.put("Connection", "keep-alive");
h.put("Keep-Alive", "300");
for (String key : h.keySet())
connection.addRequestProperty(key, h.get(key));
// Prepare parameters for Realm authenticate
StringBuilder parameter = new StringBuilder();
parameter.append("j_username").append("=").append(URLEncoder.encode(userName, "UTF-8"));
parameter.append("&");
parameter.append("j_password").append("=").append(URLEncoder.encode(userPwd, "UTF-8"));
// Post parameters
OutputStream os = connection.getOutputStream();
os.write(parameter.toString().getBytes("UTF-8"));
os.flush();
connection.connect();
// flush the output
flushOutput(connection.getInputStream());
// Check response status
// int responseStatus = connection.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
}
}
/**
* @param is
* @return
* @throws Exception
*/
private String flushOutput(InputStream is) throws Exception {
// flush the output
BufferedReader in = null;
String inputLine = null;
StringBuilder content = new StringBuilder();
try {
in = new BufferedReader(new InputStreamReader(is));
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null)
in.close();
}
return content.toString();
}
/**
* @param page
* @return an absolute URL to get the requested page
* @throws Exception
*/
private String buildAbsoluteUrl(String page) throws Exception {
return this.baseUrl.toExternalForm() + this.tomcatContext + page;
}
/**
* Configure HTTPS for HTTP Connections
*
* BE CAREFUL *************************************************************** WARNING : this might not be a good way to deal with HTTPS connections !! * BE CAREFUL ***************************************************************
*
* @throws Exception
*/
private void configureHttps() throws Exception {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
// Set at true the HostnameVerifier
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
public static void main(String[] args) {
String content = null;
URL url = null;
RealmProtectedResourceProvider provider = null;
try {
url = new URL("http://localhost:8080");
provider = new RealmProtectedResourceProvider(url, "/web", "index.do", "index.do?destroySession=true", "index.do");
// login
provider.login("mylogin", "mypwd");
// get contents
content = provider.getContent("Weather.do?viewId=105");
System.out.println(content);
content = provider.getContent("Dashboards.do?viewId=100&module=workload");
System.out.println(content);
// go on with all contents to get ...
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// logout
if (provider != null)
provider.logout();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
} |
Partager