302 Error while creating service provider in WSO2 Identity Server - java

I am trying to create a service provider in WSO2 Identity Server through Java program. The code block creating a service provider goes as follows.
public static OAuthKeySecret createOAuthServiceProvider(OAuthAppDetails oauthApp, String authType) {
OAuthKeySecret oauthKeySecret = new OAuthKeySecret();
try {
IdentityApplicationManagementServiceStub IAMStub = new IdentityApplicationManagementServiceStub(
null, oauthApp.getSERVER_URL() + "IdentityApplicationManagementService");
ServiceClient IAMClient = IAMStub._getServiceClient();
Authenticate.authenticate(IAMClient);
ServiceProvider serviceProvider = new ServiceProvider();
serviceProvider.setApplicationName(oauthApp.getAppName());
serviceProvider.setDescription(oauthApp.getAppDescription());
IAMStub.createApplication(serviceProvider);
System.out.println("Service Provider created");
} catch (Exception e) {
e.printStackTrace();
}
return oauthKeySecret;
}
When running the program I am getting the following error traced back to following line of code
IAMStub.createApplication(serviceProvider);
Complete trace
org.apache.axis2.AxisFault: Transport error: 302 Error: Found
at org.apache.axis2.transport.http.HTTPSender.handleResponse(HTTPSender.java:311)
at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:194)
at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:451)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:278)
at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:442)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:430)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:225)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:149)
at org.wso2.carbon.identity.application.mgt.stub.IdentityApplicationManagementServiceStub.createApplication(IdentityApplicationManagement
ServiceStub.java:601)
at com.xxxxx.identity.wso2.IdentityServerAdapter.IDManagementClient.createOAuthServiceProvider(IDManagementClient.java:52)
at com.xxxxx.identity.wso2.IdentityServerAdapter.IdentityServerRest$1.handle(IdentityServerRest.java:37)
at com.xxxxx.identity.wso2.IdentityServerAdapter.IdentityServerRest$1.handle(IdentityServerRest.java:19)
at spark.webserver.MatcherFilter.doFilter(MatcherFilter.java:138)
at spark.webserver.JettyHandler.doHandle(JettyHandler.java:54)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:179)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:136)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:451)
at org.eclipse.jetty.server.HttpChannel.run(HttpChannel.java:252)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:266)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConnection.java:240)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:596)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:527)
at java.lang.Thread.run(Unknown Source)
Whats going on here? Please help me.

In Identity Server 5.1.0, "createApplication" operation works without any issue. Can you please post the full sample source code and Implementation of Authenticate.authenticate? Log the values of "oauthApp.getAppName()". Below code works for me.
try {
String authCookie = null;
ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
AuthenticationAdminStub authstub = new AuthenticationAdminStub(ctx, "https://localhost:9443/services`enter code here`/AuthenticationAdmin");
ServiceClient client = authstub._getServiceClient();
Options options = client.getOptions();`enter code here`
options.setManageSession(true);
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, authCookie);
//set trust store properties required in SSL communication.
System.setProperty("javax.net.ssl.trustStore", RemoteUMSampleConstants.TRUST_STORE_PATH);
System.setProperty("javax.net.ssl.trustStorePassword", RemoteUMSampleConstants.TRUST_STORE_PASSWORD);
authstub.login("admin", "admin", "localhost");
authCookie = (String) authstub._getServiceClient().getServiceContext().getProperty(
HTTPConstants.COOKIE_STRING);
IdentityApplicationManagementServiceStub stub = new IdentityApplicationManagementServiceStub(
"https://localhost:9443/services/IdentityApplicationManagementService");
ServiceClient e = stub._getServiceClient();
Options option = e.getOptions();
option.setManageSession(true);
option.setProperty("Cookie", authCookie);
ServiceProvider serviceProvider = new ServiceProvider();
serviceProvider.setApplicationName("testName");
serviceProvider.setDescription("testDescription");
stub.createApplication(serviceProvider);
}catch (Exception e){
System.out.print(e);
}

Related

Google Maps API (Directions) throws 403 error in Payara, not in WebLogic

I've been given the task to move our application from WebLogic 12.1.3 to Payara 4.1 and have run into an issue that I feel I'm more or less at the end of the line of troubleshooting.
We have an EJB (a Stateless bean) that has two methods, one that makes a call to the Google Maps Directions API and one that makes a call to the Google Maps Geocoding API, both using the same credentials and Googles client libraries for Java. Both methods work perfectly running on WebLogic, but after switching to Payara the one using the Directions API gives me an error. Here's the relevant part of the stacktrace:
java.io.IOException: Server Error: 403 Forbidden
at com.google.maps.internal.OkHttpPendingResult.parseResponse(OkHttpPendingResult.java:258)
at com.google.maps.internal.OkHttpPendingResult.await(OkHttpPendingResult.java:167)
at com.google.maps.PendingResultBase.await(PendingResultBase.java:56)
at com.somecompany.integration.GoogleDirectionsIntegration.getDirections(GoogleDirectionsIntegration.java:XXX)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
So the geocoding-method still works on both platforms, but when attempting the call to the Directions API I get a 403 back from Google indicating that my credentials are messed up, but the very same credentials work for the geocoding call. The code hasn't been changed in any way switching from one platform to the other.
What's even more confusing is that if I grab the actual URL of the call to Google from the logs and try it in my browser, i.e. paste "https://maps.googleapis.com/maps/api/directions/json?client=gme-company&mode=driving&arrival_time=1435825037&o
rigin=Somewhere&destination=Somewhere+else&alternat
ives=false&signature=nfre3XYZ2kmuDX8Qibce87ZFKQQ=" into Chrome, it works. I get a proper answer from Google. (btw, those aren't the actual credentials or origin and destination I'm using, they've been "anonymized" :-)). I've also checked that this URL (which is built by the client library) is the same running on both platforms as well as used the URL Signing Debugger on Google's developer pages, but to no avail. There should be nothing wrong with my credentials.
I'm really at the end of the line here, having spent days troubleshooting and searching online without finding a solution.
Not that it matters that much but I didn't write this code myself, and the person who did of course doesn't work here anymore :-P
Anyway, here's the code (somewhat anonymized):
#Stateless
public class GoogleDirectionsIntegration {
private static final Logger LOGGER = Logger.getLogger(GoogleDirectionsIntegration.class.getName());
private GeoApiContext context = null;
/**
* Initializer
*/
#PostConstruct
public void init() {
LOGGER.log(Level.INFO, "initiating {0}", this.getClass().getSimpleName());
this.context = new GeoApiContext().setEnterpriseCredentials("gme-company", "companyGoogleCryptographicSecret");
this.context.setReadTimeout(1, TimeUnit.SECONDS)
.setRetryTimeout(1, TimeUnit.SECONDS)
.setConnectTimeout(1, TimeUnit.SECONDS)
.setWriteTimeout(1, TimeUnit.SECONDS);
OkHttpRequestHandler okHttpRequestHandler = null;
OkHttpClient okHttpClient = null;
try {
Field requestField = this.context.getClass().getDeclaredField("requestHandler");
requestField.setAccessible(true);
okHttpRequestHandler = (OkHttpRequestHandler) requestField.get(this.context);
Field f = okHttpRequestHandler.getClass().getDeclaredField("client");
f.setAccessible(true);
okHttpClient = (OkHttpClient) f.get(okHttpRequestHandler);
} catch (NoSuchFieldException | SecurityException | IllegalAccessException | IllegalArgumentException e) {
throw new IllegalStateException("Failed to create SSL context", e);
}
SSLContext sslCtx = this.getSslContext();
if (sslCtx != null && okHttpClient != null) {
SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
okHttpClient.setSslSocketFactory(sslSocketFactory);
}
}
private SSLContext getSslContext() {
TrustManager[] tm = new TrustManager[] {
new CustomTrustManager()
};
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, tm, new SecureRandom());
} catch (NoSuchAlgorithmException | KeyManagementException ex) {
throw new IllegalStateException("Failed to create SSL context", ex);
}
return sslContext;
}
public DirectionsRoute getDirections(final String origin, final String destination, final DistanceUnit distanceUnit,
#Nullable TransportMode mode, #NotNull Instant arrivalTime) throws NotFoundException {
TransportMode actualMode = mode == null ? TransportMode.CAR : mode;
DirectionsRoute[] directionsRoutes;
DirectionsApiRequest directionsApiRequest = DirectionsApi.getDirections(this.context, origin, destination);
directionsApiRequest.arrivalTime(new Instant(arrivalTime));
directionsApiRequest.alternatives(false);
directionsApiRequest.mode(this.toTravelMode(actualMode));
try {
DirectionsResult res = directionsApiRequest.await(); // THIS IS WHERE IT BREAKS!
directionsRoutes = res.routes;
} catch (Exception e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
throw new NotFoundException(e.getMessage());
}
if (directionsRoutes.length != 1) {
throw new NotFoundException("Failed to fetch valid directions");
}
return directionsRoutes[0];
}
public void getAddress(LatLng startLocation, Location location, boolean cacheOverride) throws Exception {
com.google.maps.model.LatLng gLatLng = new com.google.maps.model.LatLng(startLocation.getLat(), startLocation.getLng());
GeocodingApiRequest geocodingApiRequest = GeocodingApi.reverseGeocode(this.context, gLatLng);
GeocodingResult[] geocodingResults;
geocodingResults = geocodingApiRequest.await();
if (0 < geocodingResults.length) {
//.. Code that does stuff with the result..
} else {
LOGGER.log(Level.WARNING, "Received empty results from Google reverse geocode for [{0}].", startLocation);
}
}
}
So I solved it. The problem wasn't in the code but in the dependencies, or rather in a dependency to one of the dependencies - OkHttp. I simply changed the version and it works now.

java.net.Authenticator : java.net.ProtocolException: Server redirected too many times (20)

We are calling URL using proxy settings via java standalone sample code on our weblogic servers (node1/node2).
This code works fine on node 1 but same code doesn't work on node2 server.
We already checked proxy settings and credentials all are fine but still we get following error :
java.net.ProtocolException: Server redirected too many times (20)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1323)
at ProxyCode.start2(ProxyCode.java:54)
at ProxyCode.main(ProxyCode.java:23)
Exception in thread "Main Thread" java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:61)
at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
at ProxyCode.readFromInputStream(ProxyCode.java:65)
at ProxyCode.start2(ProxyCode.java:59)
at ProxyCode.main(ProxyCode.java:22)
Also , Please find my code snippet below :
SimpleAuthenticator.java
import java.net.Authenticator;
import java.net.PasswordAuthentication;
public class SimpleAuthenticator extends Authenticator
{
private String username;
private String password;
public SimpleAuthenticator(String username,String password)
{
this.username = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(
username,password.toCharArray());
}
}
Main class :
String url = "http://www.oracle.com/technetwork/java/readme-2-149793.txt";
String proxy = "proxyserver";
String port = "8080";
String username = "username";
String password = "password";
Authenticator.setDefault(new SimpleAuthenticator(username,password));
URL server = null;
try {
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
server = new URL(url);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost", proxy);
systemProperties.setProperty("http.proxyPort", port);
InputStream in = null;
URLConnection connection = null;
try {
connection = (URLConnection) server.openConnection();
connection.connect();
in = connection.getInputStream();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println(readFromInputStream(in));
}
public static String readFromInputStream(InputStream in) {
StringBuffer strBuf = new StringBuffer();
char ac[];
BufferedReader buf = new BufferedReader(new InputStreamReader(in));
try
{
while (buf.ready()) {
ac = new char[10000];
buf.read(ac);
strBuf.append(ac);
}
buf.close();
}
catch (IOException e) {
e.printStackTrace();
}
We are stuck in this since months now and not able to get any useful information anywhere.
kindly help.thanks
You will get this error if you provide wrong credentials (username or password).
This happened to me with a Glassfish based web app. I was expecting a 401 response however.
I think, the Authenticator tries the same credentials many times.
Found this open issue, still unfixed it would seem. Your user doesn't have access rights, but instead of prompting again it retries with the same user over and over
Update: The issue had another ticket open - this is apparently expected behaviour and
"To overcome this, your implementation of
Authenticator::getPasswordAuthentication needs to provide a means to
collect the correct password if the initial authentication attempt was
not successful."
See the ticket or the java.net.Authenticator documentation for more info.

Mock a server using Mockito

I am trying to test if the server will return the string. However, I want to test it without actually connecting to the server. I am trying to get rid of the java.net.SocketException by mocking the server. What approach should I do?
The code below declares all of the necessary values for the server.
#RunWith(MockitoJUnitRunner.class)
public class testTransfer {
#Test
public void getServerMessage() {
//variables
String serverhostname = "serverA";
int portNo = 8888;
int versionNo = 9999;
String protocol = "tcp";
String serverInput = "input string";
String url = "http://localhost:8080/server/url";
Service service =new Service();
Call call = Mockito.mock(Call.class);
server_string result = Mockito.mock(server_string.class);
The code below calls the server and adds values inside the xml.
//try catch
try {
call=(Call)service.createCall();
QName qn = new QName("urn:ServerApiService", "server_string" );
call.registerTypeMapping(server_string.class, qn,
new org.apache.axis.encoding.ser.BeanSerializerFactory(server_string.class, qn),
new org.apache.axis.encoding.ser.BeanDeserializerFactory(server_string.class, qn));
call.setTargetEndpointAddress( new java.net.URL(url) );
call.addParameter("arg1", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("arg2", XMLType.XSD_INT, ParameterMode.IN);
call.addParameter("arg3", XMLType.XSD_INT, ParameterMode.IN);
call.addParameter("arg4", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("arg5", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("arg6", qn, ParameterMode.OUT);
call.setOperationName( new QName(url, "getServerMessage") );
call.setReturnClass(server_string.class);
//result = (server_string) call.invoke( new Object[] {serverhostname,portNo,versionNo,protocol,serverInput} );
result = (server_string) Mockito.when(call.invoke( new Object[] {serverhostname,portNo,versionNo,protocol,serverInput} )).thenReturn(server_string.class);
System.out.println("Get server_string object from server ....");
// System.out.println("Value is "+result.value);
} catch (ServiceException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
However, I keep getting this
AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
faultSubcode:
faultString: java.net.SocketException: Connection reset
faultActor:
faultNode:
faultDetail:
{http://xml.apache.org/axis/}stackTrace:java.net.SocketException: Connection reset
I have used wiremock to good effect. It's a mocking framework specifically for this job.
You may also use JBoss and run the project. When mocking the server you need to use what #Bohemian said because it is much easier that way. However, the learning curve is high and is not recommended for emergency situations(i'm a newbie btw).

vysper server login fail

I'm making a vysper xmpp server.
Here's my code:
public static void main(String[] args) throws Exception {
XMPPServer server = new XMPPServer("myserver.org");
StorageProviderRegistry providerRegistry = new MemoryStorageProviderRegistry();
AccountManagement accountManagement = (AccountManagement) providerRegistry.retrieve(AccountManagement.class);
Entity user = EntityImpl.parseUnchecked("user#myserver.org");
accountManagement.addUser(user, "password");
server.setStorageProviderRegistry(providerRegistry);
server.addEndpoint(new TCPEndpoint())
server.setTLSCertificateInfo(new File("keystore.jks"), "boguspw");
//server.setTLSCertificateInfo(new File("bogus_mina_tls.cert"), "boguspw");
server.start();
System.out.println("Vysper server is running...");
server.addModule(new EntityTimeModule());
server.addModule(new VcardTempModule());
server.addModule(new XmppPingModule());
server.addModule(new PrivateDataModule());
}
I've tried both certificate files. (keystore.jks,bogus_mina_tls.cert)
After I start the server, it connects to it, and tries to login but it can't login.
SmackConfiguration.setPacketReplyTimeout(5000);
config = new ConnectionConfiguration("myserver.org", port, "localhost");
config.setSelfSignedCertificateEnabled(true);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
config.setSASLAuthenticationEnabled(true);
// config.setKeystorePath("keystore.jks");
// config.setTruststorePath("keystore.jks");
config.setKeystorePath("bogus_mina_tls.cert");
config.setTruststorePath("bogus_mina_tls.cert");
config.setTruststorePassword("boguspw");
XMPPConnection.DEBUG_ENABLED = true;
connection = new XMPPConnection(config);
try {
connection.connect();
} catch (XMPPException e) {
System.out.println("Error connect");
e.printStackTrace();
}
System.out.println("Connected: " + connection.isConnected());
try {
System.out.println(connection.isAuthenticated());
connection.login("user", "password");
} catch (XMPPException e) {
System.out.println("Error login");
e.printStackTrace();
}
I catch this exception:
SASL authentication PLAIN failed: incorrect-encoding: at
org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:337)
at
org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:203)
at org.jivesoftware.smack.Connection.login(Connection.java:348) at
com.protocol7.vysper.intro.WorkingClient.init(WorkingClient.java:57)
at
com.protocol7.vysper.intro.WorkingClient.(WorkingClient.java:27)
at com.protocol7.vysper.intro.Runclient.main(Runclient.java:11)
I've seen these examples (1st, 2nd) but they don't work.
At first please note that the server certificate is not used for user authentication, it is used to provide secure communication channel between client and server.
From the log you can see that your authentication method is "SASL PLAIN", using a user and password.
On the server, you are setting username/password as:
accountManagement.addUser("user#myserver.org", "password");
but on the client you're using
connection.login("user", "password");
This doesn't fit with the error message you are posting, but I'd suggest you try again with correct user/password.

problem with passing numeric parameter to web service from java client

i try to passing numeric parameter to a web service that receive the value and return it back.
this is the snippet of the web method :
#WebMethod(operationName = "getNumber")
public Integer getNumber(#WebParam(name = "i")
Integer i) {
//TODO write your implementation code here:
System.out.println("number : "+i);
return i;
}
an this is the snippet of my client code :
Map results = FastMap.newInstance();
results.put("result", "success");
String endPoint = "http://localhost:8084/ProvideWS/MathWS";
URL endpoint=null;
try{
endpoint = new URL(endPoint);
}
catch (MalformedURLException e) {
org.ofbiz.base.util.Debug.log("Location not a valid URL "+e);
// TODO: handle exception
}
Service service = null;
Call call = null;
try{
service = new Service();
call = (Call)service.createCall();
call.setTargetEndpointAddress(endpoint);
String nameSpace = "http://ws/";
String serviceName = "getNumber";
call.setOperationName(new QName(nameSpace, serviceName));
call.addParameter("i",org.apache.axis.Constants.XSD_INTEGER , ParameterMode.IN);
call.setReturnType(org.apache.axis.Constants.XSD_INTEGER);
Object msg[] = new Object[]{new Integer(5)};
for (Object o : msg) {
org.ofbiz.base.util.Debug.log("object to be sent===== "+o.toString());
}
Object ret = call.invoke(msg);
results.put("result", "result : "+ ret.toString());
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
org.ofbiz.base.util.Debug.log("exc when running soap client test : "+e);
results.put("result", "error : "+e);
}
return results;
the problem is the return value in the client always 0 (the server received the number as zero), the method i used to pass the parameter works fine when the paramater is String. I.ve tried to hard-coding the return value in server and the output in client is fine, so i thought it must be how the server retrieved the parameter is the problem.
do you have any idea why this is happen and how to solve this?
any help will be appreciated, thanks
I don't know what is causing your problem. But the first thing I would do would be to try to capture the actual request that is being sent to the server. That should give you some clues as to whether the root problem is on the client or server side.

Categories