How to authorize to HTTP server using java - java

What I do manually:
I open the URL: http://localhost:8080/webadmin/index.html enter login and password.
And click button wich is really do http get request: http://localhost:8080/rest/platform/domain/list
What I do in java:
String addr = "http://localhost:8080/rest/platform/domain/list?_dc=1325843792402"; //"http://localhost:8080/webadmin/index.html";
URL url = new URL(addr);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setUseCaches(false);
httpCon.setAllowUserInteraction(false);
httpCon.setRequestMethod("GET");
OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
out.close();
And get response: 401 Unauthorized.
Understandable why: I should create an authorised connection by entering a login and a password. But how I can do this?

On authentication using form fields in a web page, what happens is the following:
You access a login page. The server marks your session using one of the following methods:
Session cookie, present in the HTTP Response headers. You should store this cookie and resend it afterwards.
Redirect to a new URL in which the session is marked (http://localhost:8080/?sessionKey=3292n9fafjwagwao2903j2fswioanw)
(sometimes) hidden HTML form or Javascript variable which contains the session key and which is POST'ed on every click of a link.
Let us suppose the server uses cookies. You then do a POST request containing:
The cookie you received.
Your username and password in the POST data
The server now marks your session as "logged in" and may even give you a new or extra session identifier.
You then access a secured resource, providing a session identifier proving you are logged in.
You can follow this process very nicely using the Google Chrome Developer Network view (press CTRL+SHIFT+J, go to Network.
How do you translate this to Java code?
Do initial request to login page. Recover session cookie from HTTP headers.
Do a POST to the login form destination. Include the session cookie in the HTTP request header and the username/password in the POST data. Recover the session cookie from HTTP headers.
Now access the protected resource. Include the session cookies in the HTTP request header.
Of course, there are other ways of authenticating users at the webserver level (HTTP BASIC authentication, NTLM...), as explained by other answers here. The above method only works for HTML FORM-based authentication (as used by Facebook, Dropbox, ... and almost all major websites out there)

That depends on the authentication scheme. There are several possibilities, including
Basic access authentication
Digest access authentication
NTLM
Microsoft's HTTP Negotiate/SPNEGO
The server will tell you the correct scheme in its 401 answer. Look for the WWW-Authenticate HTTP header in the answer.
For doing HTTP authentication in Java, see this tutorial which contains a lot of useful information.

Related

I do not know what cookie Idea-f5324dcc=41f745e2-43a5-4a7f-8e31-1b35896e1ac6 represent

I just use spring security to create my web application.
When I input the url /welcome to get my welcome page which do not need user to be authenticated, my request Headers will have: Cookie: Idea-f5324dcc=41f745e2-43a5-4a7f-8e31-1b35896e1ac6.Once I login in, my request Headers will have: Idea-f5324dcc=41f745e2-43a5-4a7f-8e31-1b35896e1ac6; JSESSIONID=EE2933C4E8BD0FDFDD61CAA8CD65B806.
The cookie Idea-f5324dcc=41f745e2-43a5-4a7f-8e31-1b35896e1ac6 will always exists across all http requests.
I know the cookie JSESSIONID=EE2933C4E8BD0FDFDD61CAA8CD65B806 represent the session for current user,but what is Idea-f5324dcc=41f745e2-43a5-4a7f-8e31-1b35896e1ac6?

Query regarding TLS encryption

I have made two J2EE applications where in one servlet in ProjectX is performing a sendRedirect to another servlet of ProjectY via https protocol.
Code is something like
response.sendRedirect("https://ip:8443/ProjectY/servletY?id=123");
In ProjectY,
SerletY is having code as
PrintWriter pw = response.getWriter();
pw.print("Passed id is ID = " + request.getParameter("id"));
My Query is ,
since the data sent accross the network is ideally encrypted when using https, why am I able to see the url of the browser after redirecting to ServletY as
"https://ip:8443/ProjectY/servletY?id=123"
I have hidden the parameter using POST method , but my question is , is it actually encrypting data while sending from ProjectX(which was in http) to ProjectY (which is https call) ?
Thanks for you support.!!!
What's happening
There is no POST request involved.
The user opens ProjectX' site in the browser
It will respond with a HTTP 302 response because of your response.sendRedirect.
The user's browser will take the Location of the response and open it
Thus the user's browser establishes an TLS connection to ip:8443
After the TLS channel is opened, it will send a GET /ProjectY/servletY?id=123 HTTP/1.1
ProjectY will respond over the secure TLS channel.
Observations
If you call ProjectX in step 1 via plain HTTP, then the 302 response won't be encrypted and everybody who has access to your connection can see the id.
The user's browser will always see the id because it needs to follow the redirect in step 3.
The user will see the id in the address bar because the browser will show its new location.
When calling ProjectY, the id is protected because it is only sent via the TLS channel.

java get http response from target (302 - object moved) - hppt https protocols

I have the following situation that I'm still not able to manage:
I wrote a java class to read a http response from a site that receive POST parameters
I use HttpURLConnection and pass the input parameters
the result obtained is another form that redirect to another page (via HTTPS) to which I have to pass a username and a password and an hodden value. this page show the result in a target page (that is the firt url)
I made a call to this other page via HTTPS (HttpsURLConnection) and obtained a http 302 response code
I'm not able to reach the result page, since the followredirect option doesn't work when the protocol change (from http to https)
Can anyone help me please?
Hope I have succesfully explained.
Thanks in advance for support and regards.

Spring Security Logout and standalone application

I have a SOAP web service that is secured with Spring Security using basic authentication.
I've written a Swing application that accesses this web service. When the application starts, a login dialog appears where the user enters its credentials. When the user clicks the Login button, the JAXWS client is created with the given credentials. I also want to give the possibility to the logged user to logout. Spring Security requires to access a URL in order to logout. How does that work in a standalone application? Should this be done through CXF or using a simple HTTP client?
Avoid sessions altogether and have your JAXClient reauthenticate on every conn request. Configure your secuity.xml with stateless which is available from Spring Security 3.1.
It does not matter how do you implement this. The only requirement is to create HTTP GET to logout URL but your request should contain session ID of your session. Otherwise Spring cannot know which session to invalidate. So, I think that the easiest way for you is to use the same client you are currently using.
Ok, I'm not gonna argue about stateful vs. stateless. If you need to logout from your Swing app just send an HTTP GET request to the configured logout URL sending the session ID along. You don't even need Apache HttpClient for this:
String url = "http://example.com/logout";
String charset = "UTF-8";
String session = ";jsessionid=" + sessionId;
URLConnection connection = new URL(url + session).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
// ...
See https://stackoverflow.com/a/2793153/131929 (Firing a HTTP GET request) for details.
You can either append to session ID directly to the URL as shown above or send it as a regular cookie header like so:
connection.addRequestProperty("Cookie", "JSESSIONID=" + sessionId);

Acegi throws AuthenticationCredentialsNotFoundException when opening URl with BrowserLauncher 2

We have a JSF web application that uses Acegi security. We also have a standalone Java Swing application. One function of the Swing app is to load the user's home page in a browser window.
To do this we're currently using Commons HttpClient to authenticate the user with the web app:
String url = "http://someUrl/j_acegi_security_check";
HttpClient client = new HttpClient();
System.setProperty(trustStoreType, "Windows-ROOT");
PostMethod method = new PostMethod(url);
method.addParameter("j_username", "USERNAME");
method.addParameter("j_password", "PASSWORD");
int statusCode = client.executeMethod(method);
if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY ) {
Header locationHeader= method.getResponseHeader("Location");
String redirectUrl = locationHeader.getValue();
BrowserLauncher launcher = new BrowserLauncher();
launcher.openURLinBrowser(redirectUrl);
}
This returns a HTTP 302 redirect response, from which we take the redirect url and open it using BrowserLauncher 2. The url contains the new session ID, something like:
http://someUrl/HomePage.jsf;jsessionid=C4FB2F643CE48AC2DE4A8A4C354033D4
The problem we're seeing is that Acegi processes the redirect but throws an AuthenticationCredentialsNotFoundException. It seems that for some reason the authenticated credentials cannot be found in the security context.
Does anyone have an idea as to why this is happening? If anyone needs more info then I'll be happy to oblige.
Many thanks,
Richard
I have never done Acegi/SpringSecurity, but the symptoms are clear enough: some important information is missing in the request. You at least need to investigate all the response headers if there isn't something new which needs to be passed back in the header of the subsequent request. Maybe another cookie entry which represents the Acegi credentials.
But another caveat is that you in fact cannot open just the URL in a local browser instance, because there's no way to pass the necessary request headers along it. You'll need to have your Swing application act as a builtin webbrowser. E.g. get HTML response in an InputStream and render/display it somehow in a Swing frame. I would check if there isn't already an existing API for that, because it would involve much more work than you'd initially think .. (understatement).
In this case you can do Basic Authentication and set this header in every request instead of sending the jsessionid:
AUTHORIZATION:Basic VVNFUk5BTUU6UEFTU1dPUkQ=
The token VVNFUk5BTUU6UEFTU1dPUkQ= is the username and the password encoded base64.
Example:
scott:tiger
is:
c2NvdHQ6dGlnZXI=
One more thing: use SSL.

Categories