Problems with https protocol and Basic Authentication in java - java

i have to retrive a csv using https protocol and Basic Authentication in java. i used this code but the output stream retrived is an array with 250 zero. there are some error in my code?
String webPage = url_a;
String name = email;
String password = pass;
String authString = name + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URL url = new URL(webPage);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.addRequestProperty("Authorization", "Basic " + authStringEnc);
urlConnection.setRequestMethod("POST");
urlConnection.setAllowUserInteraction(false);
urlConnection.setDoInput(false);
urlConnection.setDoOutput(true);
urlConnection.connect();
final OutputStream outs = urlConnection.getOutputStream();

If you're trying to read the response, try urlConnection.getInputStrem() ...
The names input/output are viewed from your point of view (as client). So output is what you send out to server, and input is what you receive from server.

Related

Alternative of Basic Auth - Sonar Critical Vulnerability

I need to fetch the access token before making the actual call to the OAuth2-protected API.
As of now, I am doing it in the below fashion
String credential = clientId + ":" + clientSecret;
String encoding = Base64.getEncoder().encodeToString((credential).getBytes(‌"UTF‌​-8"​));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "Basic " + encoding);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
Sonar says this is Non-Compliant RSPEC-2647, therefore I want to know what are the alternatives I can use, and how to fix this issue?
--EDIT
In the body, I was passing grant_type, username, and password.
I tried adding client_id and client_secret as well and it works.
Now I have one more question, is passing these credentials in the body more secure?
String body = "grant_type="+grantType+"&username="+username+"&password="+password+"&client_id="+clientId+"&client_secret="+clientSecret;
byte[] postData = body.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
}
conn.connect();

IOException in Basic Authentication for HTTP url

I am hitting HTTP url with username:password using JAVA code. Below is my code
public static main (String args[]){
try{
String webPage = "http://00.00.000.000:8080/rsgateway/data/v3/user/start/";
String name = "abc001";
String password = "abc100";
String authString = name + ":" + password;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URL url = new URL(webPage);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization","Basic " +authStringEnc);
connection.setRequestProperty("Accept", "application/xml");
connection.setRequestProperty("Content-Type", "application/xml");
InputStream is = connection.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 (Exception e) {
e.printStackTrace();
}
}
But I am getting 401 Error
java.io.IOException: Server returned HTTP response code: 401 for URL:
same url if i hit using curl then it is returning response. below is the curl command.
curl -u abc001:abc100 http://00.00.000.000:8080/rsgateway/data/v3/user/start/
Please help me resolve this.
The code you are getting is HTTP 401 Unauthorized, which means that the server isn't interpreting your basic authentication properly.
Since you say that the curl command with the basic authentication you showed is working, I'll assume the problem is in your code.
It looks like you tried to follow this code.
The only error I can see (but I cannot test this to be sure) is that you just cast the byte[] to a String instead of encoding it with Base64.
So you should change this:
String authStringEnc = new String(authEncBytes);
to this:
String authStringEnc = Base64.getEncoder().encodeToString(authEncBytes);
Also, you want to change this:
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
to this:
byte[] authEncBytes = authString.getBytes();
byte[] authEncBytes = authString.getBytes(StandardCharsets.UTF_8);

FileNotFoundException with Urlconnection Get Request

Doing GET request with URLConnection. code is here
java.net.URL url = new java.net.URL(requestUrl);
URLConnection urlConnection = url.openConnection();
is = new BufferedInputStream(urlConnection.getInputStream());
getting java.io.FileNotFoundException whereas requested url is correct. i think it may be https ssl certificate issue. if anyone else got this issue and resolved please update.
Encode your parameter to create an URL for request.Unsupported
character in parameter value may cause to exceptions it can be a white space also.
String url = "http://url.com";
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
String param1 = "value1";
String param2 = "value2";
// ...
String query = String.format("param1=%s&param2=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset));
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
// ...
Courtsey

HTTPS Login using Java

I've a problem to login to a website via https.
I wrote this code (it works) for http access:
String user = user;
String password = psw;
String authString = user + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URLConnection connection= url.openConnection();
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.connect();
I'd like to do the same things but via https. Is it possible?
You can, please use HttpsURLConnection
Checkout sample program on http://www.mkyong.com/java/java-https-client-httpsurlconnection-example/
When specifying your URL, make sure to pass "https://..."
url.openConnection();
will return you an object that has the type of the established connection. It will always be URLConnection, but it can be a class that extends URLConnection as well. Such classes are HttpURLConnection and HttpsURLConnection (and others).
You should verify that the returned object is of type HttpsURLConnection. And if it's not, you should stop the connection (in case you want to avoid non secure connections).
if (connection instanceof HttpsURLConnection)

Zimbra SOAP API authenticate using zm_auth_token in java

I want to authenticate a user using the zm_auth_token that I dispose :
For the moment, I'm doing this :
LmcAuthRequest auth = new LmcAuthRequest();
auth.setUsername(userName);
auth.setPassword(password);
LmcAuthResponse authResp = (LmcAuthResponse) auth.invoke(serverURL);
LmcSession session = authResp.getSession();
But I want to use the zm_auth_token that I have. How to do this ???
Thnx
The zimbra Lmc methods are deprecated now ...
If you want to use SOAP they prefer doing it using ZMailBox (It doesn't work for me), I used this method :
// Create the connection where we're going to send the file.
URL url = new URL(SOAPUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
String postContent = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\">"+
"<soap:Header>" +
"<context xmlns=\"urn:zimbra\">" +
"<format type=\"js\"/>" +
"<authToken>" + authToken + "</authToken>" +
"</context>" +
"</soap:Header>" +
"<soap:Body>" +
"<GetFolderRequest xmlns=\"urn:zimbraMail\" />" +
"</soap:Body>" +
"</soap:Envelope>";
// insert your SOAP XML!!!
byte[] b = postContent.getBytes();
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty( "Content-Length", String.valueOf( b.length ) );
httpConn.setRequestProperty("Content-Type","application/soap+xml; charset=utf-8");
httpConn.setRequestMethod( "POST" );
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
// Everything's set up; send the XML that was read in to b.
OutputStream out = httpConn.getOutputStream();
out.write( b );
out.close();
// Read the response and write it to standard out.
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
// read & do something with input stream...
String s = null;
String response = "";
while((s=in.readLine()) != null){
response += s;
}
in.close();
SOAPConnectionFactory soapfactory=SOAPConnectionFactory.newInstance();
SOAPConnection soapconnection=soapfactory.createConnection();
MessageFactory messagefactory=MessageFactory.newInstance();
SOAPMessage messege=messagefactory.createMessage();
SOAPEnvelope envelop=messege.getSOAPPart().getEnvelope();
SOAPHeader header=messege.getSOAPHeader();
SOAPBody body=messege.getSOAPBody();
Name header_context=envelop.createName("context", null,"urn:zimbra");
Name auth_request=envelop.createName("AuthRequest",null,"urn:zimbraAccount");
Name account=envelop.createName("account");
Name password=envelop.createName("password");
header.addHeaderElement(header_context);
SOAPBodyElement auth_body=body.addBodyElement(auth_request);
auth_body.addChildElement(account).addAttribute(envelop.createName("by"),"name").addTextNode("abc");//(abc==your username)
auth_body.addChildElement(password).addTextNode("1234");//(1234=your password)
URL url=new URL("http://192.168.1.67/service/soap/AuthRequest");
SOAPMessage response=soapconnection.call(messege, url);
You can use Zimbra libraries for calling SOAP API. Please check this answer.

Categories

Resources