I am trying to Connect to url using URLConnection, in java with username and password.
This is the following code I am using:
package com.nivi.org.client;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.sun.jersey.core.util.Base64;
public class GetURLContent {
public static void main(String[] args) {
URL url;
try {
url = new URL("http://sampleurl.co.uk");
URLConnection conn = url.openConnection();
String username = "username";
String password = "password";
String Token = "zzzzzzzzzzzzzzzzzzzzz";
System.setProperty("http.proxyHost", "proxyhostname");
System.setProperty("http.proxyPort", "8080");
String userpass = username + ":" + password;
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
conn.setRequestProperty ("Authorization", basicAuth);
conn.setRequestProperty ("Token", Token);
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
System.out.println("br............."+br.toString());
br.close();
System.out.println("Done");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
=======================================
I am getting the following error
java.io.IOException: Server returned HTTP response code: 403 for URL:
http://sampleurl.co.uk
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625)
at com.nivi.org.client.GetURLContent.main(GetURLContent.java:63)
=======================================
First of all my question is
Are these following lines in the code are correct?
conn.setRequestProperty ("Authorization", basicAuth);
conn.setRequestProperty ("Token", Token);
Are these following lines in the code are correct?
It depends on how the actual website you are accessing implements its user authentication.
What you appear to be doing is a combination of HTTP Basic Authentication (i.e. the Authorization header), and something involving a non-standard header called Token. This may be sufficient, if the website supports Basic Authentication.
You should probably read the website's programmer documentation of how their web APIs work. If there isn't any such documentation available to you, use your browsers web development tools to identify the mechanism that the site is using when you log in via a web browser ... and attempt to get your client to behave the same way.
One thing to note is that sending a Basic authorization response in an HTTP request is insecure. Use an HTTPS request if that is an option.
Related
I want to call GET and POST API in java without using any framework. I need to use basic authentication. Can anybody help me with some tutorial link. In google I found code only in spring framework, But I am not using Spring. I am looking for code to call API with basic authentication.
I have to add new url with authentication in the below code. What modification is required if API is secured with basic auth and it is POST method. I am new to java so not much aware.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
public class NetClientGet {
public static void main(String[] args) {
try
{
System.out.println("Inside the main function");
URL weburl=new URL("http://dummy.restapiexample.com/api/v1/employees");
HttpURLConnection conn = (HttpURLConnection) weburl.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
System.out.println("Output is: "+conn.getResponseCode());
System.out.println("Output is: ");
System.setProperty("http.proxyHost", null);
//conn.setConnectTimeout(60000);
if(conn.getResponseCode()!=200)
{
System.out.println(conn.getResponseCode());
throw new RuntimeException("Failed : HTTP Error Code: "+conn.getResponseCode());
}
System.out.println("After the 2 call ");
InputStreamReader in=new InputStreamReader(conn.getInputStream());
BufferedReader br =new BufferedReader(in);
String output;
while((output=br.readLine())!=null)
{
System.out.println(output);
}
conn.disconnect();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Basic Authentication
See the RFC #2617 section 2: Basic Authentication Scheme
Add Authentication header into the request. Here's an example:
String username = "john";
String password = "pass";
// ...
URL weburl=new URL("http://dummy.restapiexample.com/api/v1/employees");
HttpURLConnection conn = (HttpURLConnection) weburl.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
// snippet begins
conn.setRequestProperty("Authorization",
"Basic " + Base64.getEncoder().encodeToString(
(username + ":" + password).getBytes()
)
);
// snippet ends
System.out.println("Output is: "+conn.getResponseCode());
POST Method
See this answer for more information about using POST method with HttpURLConnection.
I'm trying to make a request with java on this OData2 API => https://scihub.copernicus.eu/dhus/odata/v1/ for a project. But I can't without authentication. I have personal logs, as a user I don't have any problems. When I tried with java it gave an error 401.
I try this:
String auth = user + ":" + password;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
String basicAuth = "Basic " + new String(new Base64().encode(auth.getBytes()));
connection.setRequestProperty("Authorization", basicAuth);
connection.connect();
int responseCode = connection.getResponseCode();
System.out.println(responseCode);
System.out.println(url.toString());
But it doesn't works. When i print the responseCode i have a 400 error and i try also another code it was a 401 error.
With PostMan i only need the BasicAuth to have an access and it works.
And i'm using Olingo2.
I'm new on java web and i don't have any idea.
In the first step i only want to have the authentication.
And then doing queries.
Thank you!
For the 401 case there is something wrong with the authorization,otherwise the general approach is right.
For the 400 case, browsers and tools like postman will automatically send additional headers, which the code will be missing. I reused the about code and passed an additional header Accept : application/xml and was able to retrieve the response. Below is the working code. Cheers!
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class Test1 {
public static void main(String[] args) throws IOException {
String user = "ENTER YOUR USERNAME";
String password = "ENTER YOUR PASSWORD";
String auth = user + ":" + password;
URL url = new URL("https://scihub.copernicus.eu/dhus/odata/v1/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
String basicAuth = "Basic " + Base64.getEncoder().encodeToString((auth).getBytes(StandardCharsets.UTF_8)); // Java
connection.setRequestProperty("Authorization", basicAuth);
connection.connect();
System.out.println(connection.getResponseCode());
System.out.println(connection.getContent());
}
}
I created a Java Application to Connect the ASP.Net Asmx Web Service hosted in IIS 7 (Windows Server 2008 R2). The hosted site is configured to Authentication Type of Windows Authentication and provider as negotiate and ntlm
In Java Code I am using Authenticator Class to set username and password. This Code connects to the web service event if i give the password wrong. I checked the IIS logs, it actually uses the current logged on user to connect web service.
I tried debugging the Java Code after calling the getPasswordAuthentication() function java code validates the username and password using krb5 authentication method. At this point this throws an exception
"Unable to locate Kerberos realm"
But this exception is handled at the java api and i am getting the response from the web service
Our requirement is to connect the web service with the provided credentials, if the provided credentials is wrong. it should return Unauthorized Access Code.
Below is my java Code.
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.codec.binary.Base64;
public class ConnectToUrlUsingBasicAuthentication {
public static void main(String[] args) {
try {
String webPage = "http://servername/webservice/ABC.asmx/GetStudentReport";
String name = "domain.lab\\sachin";
String password = "Password123";
//NtlmHandler handler = new NtlmHandler();
Authenticator.setDefault(new NtlmAuthenticator(name, password));
String authString = name + ":" + password;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
System.out.println("Base64 encoded auth string: " + authStringEnc);
URL url = new URL(webPage);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//conn.setRequestProperty("Authorization", "Basic " +authStringEnc );
conn.connect();
System.out.println("Response Code: " + conn.getResponseCode() );
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
String result = sb.toString();
System.out.println("*** BEGIN ***");
System.out.println(result);
System.out.println("*** END ***");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Below is the NtlmAuthenticator Class
import java.net.Authenticator;
import java.net.PasswordAuthentication;
public class NtlmAuthenticator extends Authenticator {
private final String username;
private final char[] password;
public NtlmAuthenticator(final String username, final String password) {
super();
this.username = new String(username);
this.password = password.toCharArray();
}
#Override
public PasswordAuthentication getPasswordAuthentication() {
System.out.println("Scheme:" + getRequestingScheme() );
System.out.println("Host:" + getRequestingHost() );
PasswordAuthentication pa = new PasswordAuthentication(username, password);
System.out.println("UserName:" + pa.getUserName() );
System.out.println("Password:" + pa.getPassword().toString() );
return pa;
}
}
Please provide suggestion thanks in advance.
If you are running your client on windows then this behavior is as specified. The authentication process will first attempt to use the logged in user's credentials.
This is specified under the NTLM section in http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-auth.html: 'On Microsoft Windows platforms, NTLM authentication attempts to acquire the user credentials from the system without prompting the user's authenticator object'.
I have deployed jbpm-cosole on my localhost, and I have created a java application to make REST calls for process transaction. So, my question is.
As jbpm-console uses spring-security, how to send authentication request to JBPM?
After successful authentication I want to store authentication token as a java object to make further transactions without login.
or is there any another way to do that please let me know.
This is a sample code which returns the tasks list of a user. You just need to set the authentication details in request header as shown in this code. This works with jbpm-6.1.0.Final.
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class JBPMRest {
public static void getTaskSummaryList() throws Exception {
String status = "Reserved";
String actor = "krisv";
String addr = "http://localhost:8080/jbpm-console/rest/task/query?status=" + status + "&potentialOwner=" + actor;
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(addr);
String authData = "krisv" + ":" + "krisv";
String encoded = new sun.misc.BASE64Encoder().encode(authData.getBytes());
get.setHeader("Content-Type", "application/json");
get.setHeader("Authorization", "Basic " + encoded);
get.setHeader("ACCEPT", "application/xml");
HttpResponse cgResponse = client.execute(get);
String content = EntityUtils.toString(cgResponse.getEntity());
System.out.println(content);
} catch (Exception e) {
throw new Exception("Error consuming service.", e);
}
}
}
You can send basic authentication information (username + password) in the header of your REST call. The remote Java client implementation for example does this as well. If you use the remote Java client, you can reuse the same engine for subsequent calls as well.
I have configure IIS 8.0 with PHP 5.3 , along with SQL Server.
I am not sure what is going wrong. I am able to see my JSON string in web browser , when I type in URL in the browser,
But When I passed it to the code below, it is return me
IIS 8.0 Detailed Error - 401.2 - Unauthorized
401.2 Error page in my eclipse.
I am connecting to the database via Windows Authentication. Therefore , I have set Windows Authentication enabled in my IIS. I cannot able any other authentication other than Windows authentication , then my JSONstring is not return at all from the browser as well., in that case.
I have tried the solution mentioned in the below URL
http://support.microsoft.com/kb/942043
The problem still persists
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
public class JSONTester {
/**
* #param args
* #throws Exception
*/
public static void main(String[] args)
{
InputStream is = null;
String json = "";
try
{
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://localhost/hive/get_all_products.php");
httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
System.out.println(e.toString());
}
System.out.println(json);
}
}
Any help would be great .
Thanks !!!
Internet Explorer is the only browser that does the NTLM authentication using integrated mode out-of-the-box, this is why your URL works in your 'browser'. Your Java HttpClient must authenticate explicitly and answer the NTLM challenge from the server. See HttpClient NTLM Authentication:
NTLM is the most complex of the authentication protocols supported by
HttpClient. It is a proprietary protocol designed by Microsoft with no
publicly available specification... NTLM
authentication requires an instance of NTCredentials be available for
the domain name of the server or the default credentials. Note that
since NTLM does not use the notion of realms HttpClient uses the
domain name of the server as the name of the realm. Also note that the
username provided to the NTCredentials should not be prefixed with the
domain - ie: "adrian" is correct whereas "DOMAIN\adrian" is not
correct...
HttpClient provides limited support for what is known as NTLMv1, the early version of the NTLM protocol. HttpClient does not support NTLMv2 at all.
The important thing to take home is that HttpClient does not support integrated authentication. You must provide explicit credentials, which makes it always probe to bad practices because of the requirement to provide the account password explicitly. Make sure you do not store it but ask it from the user, much the same way Firefox does when visiting a site that requests an NTLM challenge.
Read The NTLM Authentication Protocol and Security Support Provider for more details.
Make sure the account you are authenticating with has rights to the files in the website directory.