System.err: java.net.UnknownHostException: Unable to resolve host "proxy01" - java

I am getting this error
System.err: java.net.UnknownHostException: Unable to resolve host "proxy01": No address associated with hostname
I am using OKHTTP. My company have two internet connections. One which requires authentication. When l make OKHTTP call using the guest network, it works as expected. But when l switch network and connect to the secured network, l get the error above. I know my company have proxy server which am suspecting is preventing outgoing network call without authentication. When l connect to the secure network and authenticate with my username and password, am able to open google.com on my phone, however, when l open my app on the phone l get the above error

You need to provide proxy settings and its authenticator while working with OKHTTP, Something like this :
Authenticator proxyAuthenticator = new Authenticator() {
#Override public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(<username>, <password>);
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
}
};
OkHttpClient client = new OkHttpClient.Builder()
.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(<proxyHost>, <proxyPort>)))
.proxyAuthenticator(proxyAuthenticator)
.build();
replace tokens <token> with their respective values.

Related

msal4j - WsTrust endpoint not found in metadata document

I am using msal4j library (1.9.1 version) to perform authentication, using OUTH2.0 and OpenId with Azure Active Directory, in the end I need to acquire token.
I was requested to do this operation through a proxy, so i tried to use code I found in msal4j documentation:
Proxy proxy = new Proxy( Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
proxyUser,
proxyPassword.toCharArray() ) ;
}
});
Set<String> scope = Collections.singleton("User.Read");
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build();
PublicClientApplication pca = PublicClientApplication.builder(clientId)
.httpClient(new MyHttpClient(proxy,sslContext.getSocketFactory(), 0, 0))
.authority("https://login.microsoftonline.com/organizations").build();
UserNamePasswordParameters paramaters = UserNamePasswordParameters
.builder(scope, user, password.toCharArray()).build();
//here I get the error
IAuthenticationResult result = pca.acquireToken(paramaters).join();
but I am getting this error on acquireToken method
java.util.concurrent.ExecutionException:
com.microsoft.aad.msal4j.MsalServiceException: WsTrust endpoint not
found in metadata document at
java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357)
at
java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1908)
Caused by: com.microsoft.aad.msal4j.MsalServiceException: WsTrust
endpoint not found in metadata document
I also tried get method instead of join, but same result.
On Workaround on this Error:
java.util.concurrent.ExecutionException:
com.microsoft.aad.msal4j.MsalServiceException: WsTrust endpoint not
found in metadata document
Using a global tenant administrator account, which is your .onmicrosoft.com account.
Please verify and make sure you have logged in with the proper account for the App you registered. This error usually occurs if you are using the wrong credentials.
username = xxxx#xxxx.onmicrosoft.com
Note: integrated Windows Authentication (IWA) supports federated users only - users created in Active Directory and backed by Azure AD. Users created directly in Azure AD without Active Directory backing (managed users) can't use this authentication flow.
For more details refer this document
For more details refer this SO Thread: WsTrust endpoint not found in metadata document

403 Forbidden error when reading mails through Graph API with valid JWT token

I need to read mails from an Outlook mailbox via Graph API. The application I am writing is a scheduled batch job without user interaction. I can't use application permissions, because of compliance reasons. The application must not be able to access all mailboxes on the tenant. I use delegated permissions for a technical user that got shared the allowed mailboxes to achieve that. I was able to get a JWT Access Token via ADAL4J and successfully called some APIs with it, but whenever I try to read a mailbox even the technical user mailbox I get a 403 forbidden.
I started with this official [sample] (https://github.com/Azure-Samples/active-directory-java-native-headless/). After setting up my Application in Azure this sample worked right away. I then changed the Graph call to "https://graph.microsoft.com/v1.0/me/messages" and suddenly I got a 403 Forbidden. To avoid permission problems I added all delegated permissions available in Azure AD to the application and provided Administrator consent for everything. That unfortunatly changed nothing. When I check the contents of my token I see the scp field containing all the permissions. Whats strange is that I can actually write the mailbox. I can write to the draft folder via Graph API. But when I take the returned message ID and try to query the same message I just created I again get a 403 Forbidden.
Getting the token
private static AuthenticationResult getAccessTokenFromUserCredentials(
String username, String password) throws Exception {
AuthenticationContext context;
AuthenticationResult result;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
context = new AuthenticationContext(AUTHORITY, false, service);
Future<AuthenticationResult> future = context.acquireToken(
"https://graph.microsoft.com", CLIENT_ID, username, password,
null);
result = future.get();
} finally {
service.shutdown();
}
return result;
}
Calling the messages endpoint:
URL url = new URL("https://graph.microsoft.com/v1.0/me/messages");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
conn.setRequestProperty("Accept","application/json");
int httpResponseCode = conn.getResponseCode();
Change the api version to beta will solve this issue.
https://graph.microsoft.com/beta/me/messages

Validating client credentials on a server using Java SimpleFramework

I am developing a SSL/TLS enabled server using the Java SimpleFramework. I am wondering how to validate client authentications on the server.
On the server side, I am extending org.simpleframework.http.core.ContainerServer and overriding the process() method as follows:
#Override
public void process(Socket socket) throws IOException {
// Ensures client authentication is required
socket.getEngine().setNeedClientAuth(true);
super.process(socket);
}
This is to make sure that clients authenticate. Note that if I remove the call to setNeedClientAuth(), my program works perfectly.
On the client side, the following code is used:
HttpClient client = new HttpClient();
Credentials defaultcreds = new UsernamePasswordCredentials("username", "password");
client.getState().setCredentials(AuthScope.ANY, defaultcreds);
GetMethod get = new GetMethod("https://url.to.server");
get.setDoAuthentication(true);
client.executeMethod(get);
When enabling authentication requirement, I get the following exception:
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
I am guessing this relates to the fact that the passed credentials is never validated.
To summarize my question, how should I proceed to validate clients on the server?

Java SOAP web service over SSL with basic authentication, connection refused

I am trying to send a SOAP request over SSL with my own little Java client and it fails with "java.net.ConnectException: Connection refused". The same request sent with SOAPUI does not fail, I get a valid response from the server.
This is the code I am trying to run:
public static void main(String[] args) throws MalformedURLException {
System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
SSLUtilities.trustAllHttpsCertificates();
URL wsdlURL = new URL(MY_WSDL_LOCATION);
QName serviceName = new QName(MY_QNAME, NAME_OF_SERVICE);
Service service = Service.create(wsdlURL, serviceName);
Order myOrder = service.getPort(Order.class);
BindingProvider portBP = (BindingProvider) myOrder;
String urlUsed = (String) portBP.getRequestContext().
get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
System.out.println("Using URL: " + urlUsed);
((BindingProvider)myOrder).getRequestContext().put(
BindingProvider.USERNAME_PROPERTY, CORRECT_USERNAME);
((BindingProvider)myOrder).getRequestContext().put(
BindingProvider.PASSWORD_PROPERTY, CORRECT_PASSWORD);
AliveRequest aliveRequest = new AliveRequest();
MerchantInfo merchInfo = new MerchantInfo();
merchInfo.setMerchantId(CORRECT_MERCHANT_ID);
aliveRequest.setMerchantInfo(merchInfo);
AliveResponse aliveResponse = myOrder.alive(aliveRequest);
}
It fails with "java.net.ConnectException: Connection refused" exception. When I build a request from the same WSDL using SOAPUI, populate the same fields with same values and enter the same basic authentication credentials, a valid response is returned.
The problem was the fact that my Java client didn't send the request through the proxy, so my own company's firewall was blocking it. Unlike my own Java client, SOAPUI actually detects the proxy settings of the system (probably reads system environment variables) when SOAPUI's proxy settings are set "auto" (default). The solution was to set the following system properties:
-Dhttps.proxySet=true
-Dhttps.proxyHost=MY_PROXY_HOST
-Dhttps.proxyPort=MY_PROXY_PORT

http 407 proxy authentication required : how to handle in java code

System.setProperty("http.proxySet", "true");
System.setProperty("java.net.useSystemProxies", "true");
System.setProperty("http.proxyHost", "192.168.1.103");
System.setProperty("http.proxyPort", "3128");
System.setProperty("http.proxyUser", "user123");
System.setProperty("http.proxyPassword", "passwD123");
url = new URL("http://www.google.co.in");
every time when I am using this code IOException throws which say HTTP response code 407.
HTTP 407 means proxy authentication required. why this problem is coming while I set proxyUser and proxyPassword.
http 401 will occur if I put wrong password but it always give me 407, means my code does not take username and password. In above code user123 is username and passwD123 is password for proxy authentication.
http://blog.vinodsingh.com/2008/05/proxy-authentication-in-java.html
I found the solution thanks Mr. Vinod Singh.
Proxy authentication in Java
The usual corporate networks provide internet access via proxy servers and at times they require authentication as well. May applications do open the connections to servers which are external to the corporate intranet. So one has to do proxy authentication programmatically. Fortunately Java provides a transparent mechanism to do proxy authentications.
Create a simple class like below-
import java.net.Authenticator;
class ProxyAuthenticator extends Authenticator {
private String user, password;
public ProxyAuthenticator(String user, String password) {
this.user = user;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password.toCharArray());
}
}
and put these lines of code before your code opens an URLConnection-
Authenticator.setDefault(new ProxyAuthenticator("user", "password"));
System.setProperty("http.proxyHost", "proxy host");
System.setProperty("http.proxyPort", "port");
Now all calls will successfully pass through the proxy authentication.
The answer to use an Authenticator is correct for the general case. However, another cause of HTTP 407 in Java 8u111 and later is if you are using BASIC authentication against the proxy.
In this case, add this system property:
-Djdk.http.auth.tunneling.disabledSchemes=
I found this out from: https://confluence.atlassian.com/kb/basic-authentication-fails-for-outgoing-proxy-in-java-8u111-909643110.html
#GauravDS
You mentioned:
http://blog.vinodsingh.com/2008/05/proxy-authentication-in-java.html
I found the solution thanks Mr. Vinod Singh.
Proxy authentication in Java
The usual corporate networks provide internet access via proxy servers and at times they require authentication as well. May applications do open the connections to servers which are external to the corporate intranet. So one has to do proxy authentication programmatically. Fortunately Java provides a transparent mechanism to do proxy authentications.
Create a simple class like below-
.
.
.
and put these lines of code before your code opens an URLConnection-
Authenticator.setDefault(new ProxyAuthenticator("user", "password"));
System.setProperty("http.proxyHost", "proxy host");
System.setProperty("http.proxyPort", "port");
Now all calls will successfully pass through the proxy authentication.
What if the site you are connecting to also requires a username/password to allow you.
Setting a Default Authenticator(Authenticator.setDefault) will fail I guess when the external site will look for authenticated user.
Any views?....Someone ?
Edit:1
Used this code earlier and was getting the error (407) Proxy Authentication Required.
I believe that was because the authentication was requested by different hosts. and when you set a default authenticator with one user/pass for one host, then the authentication will fail for other requesting host. I made the following change yesterday to SimpleAuthenticator class and now it works like a charm.
protected PasswordAuthentication getPasswordAuthentication()
{
String requestingHost = getRequestingHost();
if (requestingHost == proxyHost){
System.out.println("getPasswordAuthentication() request recieved from->" + requestingHost );
return new PasswordAuthentication(proxyuser,proxypass.toCharArray());
}
else{
System.out.println("getPasswordAuthentication() request recieved from->" + requestingHost );
return new PasswordAuthentication(sharepointusername,sharepointpassword.toCharArray());
}
}
More info here: http://blog.ashwani.co.in/blog/2013-07-29/access-sharepoint-webservices-from-java-behind-proxy/

Categories

Resources