am trying to send a request to the identity server but don't know how to do it. I know that identity server can help you test your policy by generating a request for you within the identity server but I don't know how to do this outside the identity server. So my question is how do I sent requests to identity server in order to have it check the request against the policy and return to me a result. I have tried the blog at http://hasini-gunasinghe.blogspot.com/2011/12/entitlement-service-xacml-pdp-as-web.html and it is not working. thank you
I tried the code in the blogpost and could get it worked with the following settings with WSO2 Identity Server 4.1.0 in localhost. Don't forget to give correct path to the wso2carbon.jks.
import org.apache.axis2.AxisFault;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub;
import org.wso2.carbon.identity.entitlement.stub.EntitlementServiceStub;
import org.wso2.carbon.identity.entitlement.ui.client.EntitlementServiceClient;
public class EntitlementClient {
private static String serverUrl = "https://localhost:9443/services/";
private AuthenticationAdminStub authstub = null;
private static ConfigurationContext ctx;
private static String authCookie = null;
private static EntitlementServiceClient entitlementServiceClient;
private static EntitlementServiceStub stub;
//sample XACML request captured from TryIt tool of IdentityServer.
private static String sampleRequest = "<Request xmlns=\"urn:oasis:names:tc:xacml:2.0:context:schema:os\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <Resource>\n" +
" <Attribute AttributeId=\"urn:oasis:names:tc:xacml:1.0:resource:resource-id\"\n" +
" DataType=\"http://www.w3.org/2001/XMLSchema#string\">\n" +
" <AttributeValue>ABCResource</AttributeValue>\n" +
" </Attribute>\n" +
" </Resource>\n" +
" <Subject>\n" +
" <Attribute AttributeId=\"urn:oasis:names:tc:xacml:1.0:subject:subject-id\"\n" +
" DataType=\"http://www.w3.org/2001/XMLSchema#string\">\n" +
" <AttributeValue>admin</AttributeValue>\n" +
" </Attribute>\n" +
" <Attribute AttributeId=\"http://wso2.org/claims/role\"\n" +
" DataType=\"http://www.w3.org/2001/XMLSchema#string\">\n" +
" <AttributeValue>admin</AttributeValue>\n" +
" </Attribute>\n" +
" </Subject>\n" +
" <Action>\n" +
" <Attribute AttributeId=\"urn:oasis:names:tc:xacml:1.0:action:action-id\"\n" +
" DataType=\"http://www.w3.org/2001/XMLSchema#string\">\n" +
" <AttributeValue>read</AttributeValue>\n" +
" </Attribute>\n" +
" </Action>\n" +
" <Environment/>\n" +
"</Request>";
public static void main(String[] args) {
try {
//set trust store properties required in SSL communication.
System.setProperty("javax.net.ssl.trustStore",
"/home/pushpalanka/Servers/wso2is-4.1.1/repository/resources/security/wso2carbon.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
//initialize authentication admin stub
EntitlementClient remoteEntitlementClient = new EntitlementClient();
//login using authentication admin stub providing valid credentials
remoteEntitlementClient.login("admin", "admin");
//initialize entitlement service stub with obtained authentication cookie
remoteEntitlementClient.initEntitlementClient();
//invoke EntitlementService by passing the XACML request and obtain the authorization decision
String decision = entitlementServiceClient.getDecision(sampleRequest);
//print the authorization decision
System.out.println(decision);
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public EntitlementClient() {
try {
ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
String authEPR = serverUrl + "AuthenticationAdmin";
authstub = new AuthenticationAdminStub(ctx, authEPR);
ServiceClient client = authstub._getServiceClient();
Options options = client.getOptions();
options.setManageSession(true);
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, authCookie);
} catch (AxisFault axisFault) {
axisFault.printStackTrace();
}
}
public String login(String username, String password) throws Exception {
//String cookie = null;
boolean loggedIn = authstub.login(username, password, "127.0.0.1");
if (loggedIn) {
System.out.println("The user " + username + " logged in successfully.");
authCookie = (String) authstub._getServiceClient().getServiceContext().getProperty(
HTTPConstants.COOKIE_STRING);
} else {
System.out.println("Error logging in " + username);
}
return authCookie;
}
public void initEntitlementClient() throws AxisFault {
entitlementServiceClient = new EntitlementServiceClient(authCookie, serverUrl, ctx);
}
}
Reference - http://hasini-gunasinghe.blogspot.com/2011/12/entitlement-service-xacml-pdp-as-web.html
Related
I have a user pool in Amazon Cognito used for authenticating the APIs. And I have a user table in my database RDS where user will be inserted via application and website. I am looking for a way to auto insert user in Cognito user pool when user gets inserted in user table.
I am using java as the programming language.
Can anyone please suggest me any possible solution for it?
Can I use lambda for this? And if I can, is there any example for it, where users are inserted using lambda using java sdk?
You can use the AWS SDK for Java v2 to perform this task. To add a user to a user Pool, you can use this Java code. Specifically, you use the software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient and use the signUp method.
If you are not familiar with the AWS SDK for Java V2, refer to the DEV Guide.
Code to add a user to a user pool is:
package com.example.cognito;
//snippet-start:[cognito.java2.new_admin_user.import]
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminCreateUserRequest;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminCreateUserResponse;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AttributeType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;
import java.util.ArrayList;
import java.util.List;
//snippet-end:[cognito.java2.new_admin_user.import]
/**
* Before running this Java V2 code example, set up your development environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*/
public class CreateUser {
public static void main(String[] args) {
final String usage = "\n" +
"Usage:\n" +
" <userPoolId> <userName> <email> <password>\n\n" +
"Where:\n" +
" userPoolId - The Id value for the user pool where the user is created.\n\n" +
" userName - The user name for the new user.\n\n" +
" email - The email to use for verifying the user.\n\n" +
" password - The password for this user.\n\n" ;
if (args.length != 4) {
System.out.println(usage);
System.exit(1);
}
String userPoolId = args[0];
String userName = args[1];
String email = args[2];
String password = args[3];
CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder()
.region(Region.US_EAST_1)
.credentialsProvider(ProfileCredentialsProvider.create())
.build();
createNewUser(cognitoClient, userPoolId, userName, email, password);
cognitoClient.close();
}
//snippet-start:[cognito.java2.add_login_provider.main]
public static void createNewUser(CognitoIdentityProviderClient cognitoClient,
String userPoolId,
String name,
String email,
String password){
try{
AttributeType userAttrs = AttributeType.builder()
.name("email")
.value(email)
.build();
AttributeType userAttrs1 = AttributeType.builder()
.name("autoVerifyEmail")
.value("true")
.build();
List<AttributeType> userAttrsList = new ArrayList();
userAttrsList.add(userAttrs);
userAttrsList.add(userAttrs1);
AdminCreateUserRequest userRequest = AdminCreateUserRequest.builder()
.userPoolId(userPoolId)
.username(name)
.temporaryPassword(password)
.userAttributes(userAttrs)
.messageAction("SUPPRESS")
.build() ;
AdminCreateUserResponse response = cognitoClient.adminCreateUser(userRequest);
System.out.println("User " + response.user().username() + "is created. Status: " + response.user().userStatus());
} catch (CognitoIdentityProviderException e){
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
//snippet-end:[cognito.java2.add_login_provider.main]
}
Code to sign up a user is:
//snippet-sourcedescription:[SignUp.java demonstrates how to register a user in the specified Amazon Cognito user pool.]
//snippet-keyword:[AWS SDK for Java v2]
//snippet-keyword:[Code Sample]
//snippet-keyword:[Amazon Cognito]
//snippet-sourcetype:[full-example]
//snippet-sourcedate:[05/18/2022]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.example.cognito;
//snippet-start:[cognito.java2.signup.import]
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;
import software.amazon.awssdk.services.cognitoidentityprovider.model.SignUpRequest;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AttributeType;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
//snippet-end:[cognito.java2.signup.import]
/**
* To run this Java code example, you need to create a client app in a user pool with a secret key. For details, see:
* https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html
*
* In addition, set up your development environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*
*/
public class SignUpUser {
public static void main(String[] args) {
final String usage = "\n" +
"Usage:\n" +
" <clientId> <secretkey> <userName> <password> <email>\n\n" +
"Where:\n" +
" clientId - The app client id value that you can obtain from the AWS Management Console.\n\n" +
" secretkey - The app client secret value that you can obtain from the AWS Management Console.\n\n" +
" userName - The user name of the user you wish to register.\n\n" +
" password - The password for the user.\n\n" +
" email - The email address for the user.\n\n";
if (args.length != 5) {
System.out.println(usage);
System.exit(1);
}
String clientId = args[0];
String secretKey = args[1];
String userName = args[2];
String password = args[3];
String email = args[4];
CognitoIdentityProviderClient identityProviderClient = CognitoIdentityProviderClient.builder()
.region(Region.US_EAST_1)
.credentialsProvider(ProfileCredentialsProvider.create())
.build();
signUp(identityProviderClient, clientId, secretKey, userName, password, email);
identityProviderClient.close();
}
//snippet-start:[cognito.java2.signup.main]
public static void signUp(CognitoIdentityProviderClient identityProviderClient,
String clientId,
String secretKey,
String userName,
String password,
String email) {
AttributeType attributeType = AttributeType.builder()
.name("email")
.value(email)
.build();
List<AttributeType> attrs = new ArrayList<>();
attrs.add(attributeType);
try {
String secretVal = calculateSecretHash(clientId, secretKey, userName);
SignUpRequest signUpRequest = SignUpRequest.builder()
.userAttributes(attrs)
.username(userName)
.clientId(clientId)
.password(password)
.secretHash(secretVal)
.build();
identityProviderClient.signUp(signUpRequest);
System.out.println("User has been signed up");
} catch(CognitoIdentityProviderException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
}
public static String calculateSecretHash(String userPoolClientId, String userPoolClientSecret, String userName) throws NoSuchAlgorithmException, InvalidKeyException {
final String HMAC_SHA256_ALGORITHM = "HmacSHA256";
SecretKeySpec signingKey = new SecretKeySpec(
userPoolClientSecret.getBytes(StandardCharsets.UTF_8),
HMAC_SHA256_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
mac.init(signingKey);
mac.update(userName.getBytes(StandardCharsets.UTF_8));
byte[] rawHmac = mac.doFinal(userPoolClientId.getBytes(StandardCharsets.UTF_8));
return java.util.Base64.getEncoder().encodeToString(rawHmac);
}
//snippet-end:[cognito.java2.signup.main]
}
This code example assumes that the user pool requires a Client secret when adding a user. More info here:
Configuring a user pool app client
After you get the user details from the database, use this Cognito code to add the user to a user pool. Notice you need these input values:
clientId - The app client id value that you can obtain from the AWS Management Console.\n\n" +
secretkey - The app client secret value that you can obtain from the AWS Management Console.\n\n" +
userName - The user name of the user you wish to register.\n\n" +
password - The password for the user.\n\n" +
email - The email address for the user.\n\n";
This Java code can be wrapped in an AWS Lambda function that uses the Java Lambda runtime API.
In my project there is a need for creating share link for external users without aws user from my researching found out a couple ways for doing so
Bucket policy based on tag
Lambda that creates sign url every time some user request the file
The question is what is the best practice for doing so
I need the download to be available until the user sharing the file stopes it
Thank guys for any answers
Using the AWS SDK, you can use Amazon S3 Pre-sign functionality. You can perform this task in any of the supported programming languages (Java, JS, Python, etc).
The following code shows how to sign an object via the Amazon S3 Java V2 API.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.time.Duration;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest;
import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
import software.amazon.awssdk.utils.IoUtils;
// snippet-end:[presigned.java2.getobjectpresigned.import]
/**
* To run this AWS code example, ensure that you have setup your development environment, including your AWS credentials.
*
* For information, see this documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*/
public class GetObjectPresignedUrl {
public static void main(String[] args) {
final String USAGE = "\n" +
"Usage:\n" +
" GetObjectPresignedUrl <bucketName> <keyName> \n\n" +
"Where:\n" +
" bucketName - the Amazon S3 bucket name. \n\n"+
" keyName - a key name that represents a text file. \n\n";
if (args.length != 2) {
System.out.println(USAGE);
System.exit(1);
}
String bucketName = args[0];
String keyName = args[1];
Region region = Region.US_WEST_2;
S3Presigner presigner = S3Presigner.builder()
.region(region)
.build();
getPresignedUrl(presigner, bucketName, keyName);
presigner.close();
}
// snippet-start:[presigned.java2.getobjectpresigned.main]
public static void getPresignedUrl(S3Presigner presigner, String bucketName, String keyName ) {
try {
GetObjectRequest getObjectRequest =
GetObjectRequest.builder()
.bucket(bucketName)
.key(keyName)
.build();
GetObjectPresignRequest getObjectPresignRequest = GetObjectPresignRequest.builder()
.signatureDuration(Duration.ofMinutes(10))
.getObjectRequest(getObjectRequest)
.build();
// Generate the presigned request
PresignedGetObjectRequest presignedGetObjectRequest =
presigner.presignGetObject(getObjectPresignRequest);
// Log the presigned URL
System.out.println("Presigned URL: " + presignedGetObjectRequest.url());
HttpURLConnection connection = (HttpURLConnection) presignedGetObjectRequest.url().openConnection();
presignedGetObjectRequest.httpRequest().headers().forEach((header, values) -> {
values.forEach(value -> {
connection.addRequestProperty(header, value);
});
});
// Send any request payload that the service needs (not needed when isBrowserExecutable is true)
if (presignedGetObjectRequest.signedPayload().isPresent()) {
connection.setDoOutput(true);
try (InputStream signedPayload = presignedGetObjectRequest.signedPayload().get().asInputStream();
OutputStream httpOutputStream = connection.getOutputStream()) {
IoUtils.copy(signedPayload, httpOutputStream);
}
}
// Download the result of executing the request
try (InputStream content = connection.getInputStream()) {
System.out.println("Service returned response: ");
IoUtils.copy(content, System.out);
}
} catch (S3Exception e) {
e.getStackTrace();
} catch (IOException e) {
e.getStackTrace();
}
// snippet-end:[presigned.java2.getobjectpresigned.main]
}
}
The code below provides the ability to upload a zip archive to a AWS s3 presigned URL. I resorted to using HttpURLConnection to conduct the upload, but it seems to block on getResponse. I am looking to implement a feedback loop so that I can print the progress of upload completed.
How I can go about capturing progress of upload that I can print to stdout?
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.HttpMethod;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
public class App {
private static String bucketName = "XXXXX";
private static String objectKey = "XXXX/file.zip";
public static void main(String[] args) throws Exception {
URL url = getPresignedUrl();
uploadToUrlHTTP(url,new File("/XXX/XXXX/file.zip"));
}
public static URL getPresignedUrl() {
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new ProfileCredentialsProvider("default")).build();
try {
System.out.println("Generating pre-signed URL.");
java.util.Date expiration = new java.util.Date();
long milliSeconds = expiration.getTime();
milliSeconds += 1000 * 60 * 60; // Add 1 hour.
expiration.setTime(milliSeconds);
GeneratePresignedUrlRequest generatePresignedUrlRequest =
new GeneratePresignedUrlRequest(bucketName, objectKey);
generatePresignedUrlRequest.setMethod(HttpMethod.PUT);
generatePresignedUrlRequest.setExpiration(expiration);
URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
System.out.println("Pre-Signed URL = " + url.toString());
return url;
} catch (AmazonServiceException exception) {
System.out.println("Caught an AmazonServiceException, " +
"which means your request made it " +
"to Amazon S3, but was rejected with an error response " +
"for some reason.");
System.out.println("Error Message: " + exception.getMessage());
System.out.println("HTTP Code: " + exception.getStatusCode());
System.out.println("AWS Error Code:" + exception.getErrorCode());
System.out.println("Error Type: " + exception.getErrorType());
System.out.println("Request ID: " + exception.getRequestId());
return null;
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, " +
"which means the client encountered " +
"an internal error while trying to communicate" +
" with S3, " +
"such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
return null;
}
}
public static void uploadToUrlHTTP(URL url, File file) {
HttpURLConnection connection;
try {
InputStream inputStream = new FileInputStream(file);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
OutputStream out =
connection.getOutputStream();
byte[] buf = new byte[1024];
int count;
int total = 0;
long fileSize = file.length();
while ((count =inputStream.read(buf)) != -1)
{
if (Thread.interrupted())
{
throw new InterruptedException();
}
out.write(buf, 0, count);
total += count;
int pctComplete = new Double(new Double(total) / new Double(fileSize) * 100).intValue();
System.out.print("\r");
System.out.print(String.format("PCT Complete: %d", pctComplete));
}
System.out.println();
out.close();
inputStream.close();
System.out.println("Finishing...");
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
System.out.printf("Successfully uploaded.");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I am developing a Java client which will create an application in WSO2 Identity Server through calling the OAuthAdminService. After some digging I found that registerOAuthApplicationData() method is the one used for creating an application in IS. Before calling the method, I have authenticated the admin user via login() method of AuthenticationAdminStub type. Even after such authentication the registerOAuthApplicationData() method make the IS console to print
[2016-04-26 13:08:52,577] WARN
{org.wso2.carbon.server.admin.module.handler.AuthenticationHandler} -
Illegal access attempt at [2016-04-26 13:08:52,0577] from IP address
127.0.0.1 while trying to authenticate access to service OAuthAdminService
and the application is not getting created in the IS database.
The code which I have tried goes as follows
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.wso2.carbon.authenticator.proxy.AuthenticationAdminStub;
import org.wso2.carbon.identity.oauth.OAuthAdminServicePortTypeProxy;
import org.wso2.carbon.identity.oauth.dto.xsd.OAuthConsumerAppDTO;
public class IdentityClientOne {
private final static String SERVER_URL = "https://localhost:9443/services/";
private final static String APP_ID = "myapp";
/**
* #param args
*/
public static void main(String[] args) {
AuthenticationAdminStub authstub = null;
ConfigurationContext configContext = null;
System.setProperty("javax.net.ssl.trustStore", "wso2carbon.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
try {
configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
"repo", "repo/conf/client.axis2.xml");
authstub = new AuthenticationAdminStub(configContext, SERVER_URL
+ "AuthenticationAdmin");
// Authenticates as a user having rights to add users.
if (authstub.login("admin", "admin", APP_ID)) {
System.out.println("admin authenticated");
OAuthConsumerAppDTO consumerApp = new OAuthConsumerAppDTO("Oauth-2.0",
"sample_app",
"",
"authorization_code implicit password client_credentials refresh_token urn:ietf:params:oauth:grant-type:saml2-bearer iwa:ntlm","","","");
OAuthAdminServicePortTypeProxy OAuthAdminProxy = new OAuthAdminServicePortTypeProxy();
OAuthAdminProxy.registerOAuthApplicationData(consumerApp);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Please help what should be done right ?
You have to access the stub via the authenticated session.
Could you try below.
public class Test {
private final static String SERVER_URL = "https://localhost:9443/services/";
public static void main(String[] args) throws RemoteException, OAuthAdminServiceException {
OAuthAdminServiceStub stub = new OAuthAdminServiceStub(null, SERVER_URL + "OAuthAdminService");
ServiceClient client = stub._getServiceClient();
authenticate(client);
OAuthConsumerAppDTO consumerAppDTO = new OAuthConsumerAppDTO();
consumerAppDTO.setApplicationName("sample-app");
consumerAppDTO.setCallbackUrl("http://localhost:8080/playground2/oauth2client");
consumerAppDTO.setOAuthVersion("OAuth-2.0");
consumerAppDTO.setGrantTypes("authorization_code implicit password client_credentials refresh_token "
+ "urn:ietf:params:oauth:grant-type:saml2-bearer iwa:ntlm");
stub.registerOAuthApplicationData(consumerAppDTO);
}
public static void authenticate(ServiceClient client) {
Options option = client.getOptions();
HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
auth.setUsername("admin");
auth.setPassword("admin");
auth.setPreemptiveAuthentication(true);
option.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth);
option.setManageSession(true);
}
}
Getting Error while consuming webservices in java through SOAP approach. Plz suggest, i am stuck in this for last 10 days. I am using this server for webservices "http://www.webservicex.net/globalweather.asmx"
Error:
Exception in thread "main" [SOAPException: faultCode=SOAP-ENV:Client; msg=Error
opening socket: Connection timed out: connect;
targetException=java.lang.IllegalArgumentException: Error opening
socket: Connection timed out: connect]
at org.apache.soap.transport.http.SOAPHTTPConnection.se(SOAPHTTPConnection.java:324)
at org.apache.soap.rpc.Call.invoke(Call.java:205)
at com.check.ClientNet.main(ClientNet.java:47)
My java code is :
package com.check;
import java.net.*;
import java.util.*;
import org.apache.soap.*;
import org.apache.soap.encoding.SOAPMappingRegistry;
import org.apache.soap.rpc.*;
import org.apache.soap.encoding.soapenc.StringDeserializer;
import org.apache.soap.util.xml.QName;
import com.check.ProxyAuthenticator;
public class ClientNet {
public static void main (String[] args)
throws Exception {
Properties properties = System.getProperties();
properties.put("http.proxyHost", "10.136.236.30");
properties.put("http.proxyPort", "8080");
properties.put("http.proxyUser", "bnkishore");
properties.put("http.proxyPassword","XXXX");
Properties newprops = new Properties(properties);
System.setProperties(newprops);
String username = System.getProperty("http.proxyUser");
String password = System.getProperty("http.proxyPassword");
if (username != null && !username.equals("")) {
Authenticator.setDefault(new ProxyAuthenticator(username, password));
}
System.out.println("\n\nCalling the SOAP Server:\n\n");
//http://www.webservicex.net/globalweather.asmx
URL url = new URL ("http://www.webservicex.net/globalweather.asmx");
String CountryName = "India";
Call call = new Call();
SOAPMappingRegistry soapMappingRegistry = new SOAPMappingRegistry();
soapMappingRegistry.mapTypes(Constants.NS_URI_SOAP_ENC, new QName("http://www.webserviceX.NET", "globalweather"),null,null, new StringDeserializer());
call.setTargetObjectURI("http://www.webserviceX.NET");
call.setMethodName("GetCitiesByCountry");
call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
Vector<Parameter> params = new Vector<Parameter>();
params.addElement(new Parameter("CountryName", String.class, CountryName, null));
call.setParams (params);
System.out.print("The SOAP Server says: ");
Response resp = call.invoke(url, " ");
if (resp.generatedFault()) {
Fault fault = resp.getFault();
System.out.println("\nOuch, the call failed: ");
System.out.println(" Fault Code = " + fault.getFaultCode());
System.out.println(" Fault String = " + fault.getFaultString());
} else {
Parameter result = resp.getReturnValue();
System.out.print(result.getValue());
System.out.println();
}
}
}
And ProxyAuthencator code is :
package com.check;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
public class ProxyAuthenticator extends Authenticator {
private String userName, passWord;
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName,passWord.toCharArray());
}
public ProxyAuthenticator(String userName, String password) {
this.userName = userName;
this.passWord = password;
getPasswordAuthentication();
}
}
Thanks.
There is a timeout, that means you client is not reaching the server. Check connectivity. For dealing with a proxy, additionally to your ProxyAuthenticator you need to add few system properties: proxySet, proxyHost and proxyPort. If you are using maven, you can do it in this way:
mvn jetty:run -DproxySet=true -DproxyHost=proxy.indra.es -DproxyPort=8080