Unable to call webservice from Java in flex application - java

Hello I face some problem, I'm not able to to call webservice from java and send the result to flex side.
the process
the user launches the application and lands on an authentication form
The user enters login and password and submits the authentication form
Submission call on java side a remoteservice checkUserCredetialFromLdap()
inside this java method I try to call an external ldap webservice as shown below.
The class responsible for ldap ws call is in custom jar (Maven dependencies)
public User checkUserCredetialFromLdap(String identifiant, String password) throws EmmBusinessException, LdapServiceException{
User myUser = null;
User myCompleteUser = null;
//initialization of webservice with the endpoint URL failed
Axis1LdapWsAuth ws = new Axis1LdapWsAuth(Config.getProperties().getProperty("endpoint.url"));
try{
//authentication using webservice
String csif_sessionID =ws.login(identifiant, password);
....
}
}catch(LdapServiceException lse)
{
EmmBusinessException emmB = new EmmBusinessException(lse,this,"","Unable to get User",Level.WARNING);
log(emmB);
throw (emmB);
}
catch (Exception t) {
EmmBusinessException emmB = new EmmBusinessException(t,this,"","Unable to get User",Level.WARNING);
log(emmB);
throw (emmB);
} finally {
finish();
}
return myCompleteUser;
}
I know it's possible to call webservice on flex side using RPC, but I don't want to do that, but for some reason I need to and have to call webservice from java side.
is't possible ? How can I do that ?

I suggest you to:
Develop a kind of proxy ldap webservice whose will do the bridge between flex app and your custom ldap authentication process
Use HttpService from flex to send parameter to the proxy ldap
Use proxy ldap to consume the checkUserCredetialFromLdap api with parameter get from flex

Related

Restful service in MS Dynamics

I have a requirement to create restful service using WebApi in MS Dynamics and create a client in Java and hit the MS Dynamics Web Service. If I want to create a restful service in MS Dynamics through WebApi, is it mandatory that I need to have OAUTH implemented? Can create a service and hit from Java without authentication?
My another question is, is it possible to use our custom authentication method like call a another web service from MS Dynamics and validate and if authorised user then send data.
I am ok in implementing Java client but I am not familiar with MS Dynamics and not able to find any help from net.
Here's an example from Jason Lattimer's blog post: CRM Web API Using Java
Again our friends at Microsoft help us out on the authentication front
by providing a version of the Azure Active Directory Authentication
Library (ADAL) for Java. You can set up a Maven dependency with the
info here:
http://mvnrepository.com/artifact/com.microsoft.azure/adal4j
In this case I’m authentication using a hardcoded username and
password.
//Azure Application Client ID
private final static String CLIENT_ID = "00000000-0000-0000-0000-000000000000";
//CRM URL
private final static String RESOURCE = "https://org.crm.dynamics.com";
//O365 credentials for authentication w/o login prompt
private final static String USERNAME = "administrator#org.onmicrosoft.com";
private final static String PASSWORD = "password";
//Azure Directory OAUTH 2.0 AUTHORIZATION ENDPOINT
private final static String AUTHORITY =
"https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000";
AuthenticationContext context = null;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
context = new AuthenticationContext(AUTHORITY, false, service);
Future<AuthenticationResult> future = context.acquireToken(RESOURCE,
CLIENT_ID,
USERNAME,
PASSWORD, null);
result = future.get();
} finally {
service.shutdown();
}
String token = result.getAccessToken();
The other thing I stumbled upon is that Java’s HttpURLConnection for
making HTTP requests doesn’t support the PATCH method natively (which
is used by the Web API when doing updates to multiple fields). This
was solved specifying a POST method and adding an additional
“X-HTTP-Method-Override” property.
connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
connection.setRequestMethod("POST");
You can check out the code on GitHub:
https://github.com/jlattimer/CrmWebApiJava

Providing oauth credentials from ios client and app engine endpoint

I am working on app engine endpoints (back end), i have created credentials for ios, web application and others, client id and Client secret are generated (same id are added as part of endpoint code ). Now i assume app engine endpoint requests are authorized by oauth from the IOS and when call it from api-explorer. My questions are
When endpoints are tested through api-explorer, without client id i am able to get success response. Is it something i need to do, so that oauth is the first level of security always ?
#Api(name = "myapp", version = "v1", description = "myapp cloud-endpoint",
clientIds = {Constants.WEB_CLIENT_ID, Constants.IOS_CLIENT_ID})
public class YourFirstAPI {
How to give client id and Client secret from IOS client while consuming app engine endpoints ?
Please help me on this.
Endpoints auth is optional. If you need to require auth, currently you need to inject the User parameter into your API methods and check them manually. For example,
public void apiMethod(User user) {
if (user == null) {
throw new UnauthorizedException();
}
...
}
I suggest you check out the Rest iOS client docs.

How to manage client/server session data using jersey 2.19 REST API

I am new to REST and am trying to figure out an issue with giving access to users to the REST API data
I have an application where Users have limited rights to what they can see based on their user ID.
I do this through something similar to below:
#Component
public class StudentsResource{
#Path("students")
#GET
#Produces(MediaType.APPLICATION_JSON_VALUE)
public Students getStudents(#Context HttpServletRequest request){
final HttpSession session = request.getSession();
User user = (User) session.getAttribute(RestConstants.USER);
if(user == null){
throw new NotLoggedInException(RestConstants.USER_NOT_LOGGED_IN);
}
Students students = new Students();
return students;
}
}
If I login to the application, and then paste the URL for the REST URL into the browser localhost:8080/api/students I get the JSON response of /students. If I don't login to the application first and instead just navigate to the URL localhost:8080/api/students in the browser, I get the error that I am not authorized because I am not logged into the application. (So that works just as I want)
However, if I build a webpage in the app that uses client code to call the API where pressing a button will run:
String restURL = "http://localhost:8080/localhost:8080/api/students";
final RestTemplate rest = new RestTemplate();
Students response = rest.getForObject(restURL,Students.class);
I then login to the app, and run the above code by pressing the button (instead of just navigating to the URL in the browser), I get an error that I am not logged in, so I do not have permission to see the data.
Upon further investigation, I saw that this is because the session that I am getting in my server side code has null for the logged in user when pressing the button on the client side, but it has the correct user when just navigating to the URL in the browser.
Why is this value null when using the client code if I logged in, but it works by navigating to the URL?
How can I get the correct Session data to get the logged in user when using the Client code/button?
You can achieve client/server communication by token based authentication mechanism, basically what you do is after user login into our system, we generate a random UUid and concatenate it with userid,Encode it with Base64 algorithm and send it back to client as a token,
Then from the next request onward the user need to send the token in the header, form the header we can identify which user is accessing the service.
for more information chekout the below link, it is a good blog for all the details regarding Jax-Rs
https://abhirockzz.wordpress.com/

Authenticate SOAP WebService

I'm trying to develop a SOAP WebService client in Java, and I'm unable to authenticate to it.
I have user and password from my provider and the wsdl is this:
https://www.ictower.net/Services/MasterService.svc?wsdl
With eclipse I generate the service clases and a Stub class, but when I try to authenticate, always get this message
An error occurred when verifying security for the message.
I have tried
IMasterServiceProxy ICTService = new IMasterServiceProxy();
MasterServiceLocator ICTLocator = new MasterServiceLocator();
URL urlServicio = new URL("https://www.ictower.net/Services/MasterService.svc");
BasicHttpBinding_IMasterServiceStub stub = new BasicHttpBinding_IMasterServiceStub(urlServicio, ICTLocator);
stub.setUsername("XXXXX");
stub.setPassword("XXXXX");
I also tried with _setProperty instead of the setters
stub._setProperty(BasicHttpBinding_IMasterServiceStub.USERNAME_PROPERTY, "XXXXX");
stub._setProperty(BasicHttpBinding_IMasterServiceStub.PASSWORD_PROPERTY, "XXXXX");
but always when I call any service method, always same return (error verifying security...)
I'm completly lost, I have expend hours trying and searching... Any help is welcome

Java web service client generated in Netbeans - getting Http Status Code 307

I use Netbeans to generate web service client code, client-style JAX-WS, so i can invoke a web service API.
However, when I invoke the web service API, I get the exception:
com.sun.xml.internal.ws.client.ClientTransportException: The server sent HTTP status code 307: Temporary Redirect
Why do I get this? What is the workaround? I know the problem isn't with the web service itself, because I can get responses fine via soapUI and .Net.
Faced the same problem about a month ago.
Web service client classes were generated using Apache CXF and web service returned HTTP
status 307, which led to the same exception.
Invocation of the same web service method using soapUI with property Follow Redirects set to true was successful and returned needed data.
After googling awhile, it looked like there is no property to enable following redirects in the JAX-WS for this.
So, below is the code which is currently working, though I'm not sure it is compliant with any standards:
Supposing generated client classes looks like:
// generated service class
public class MyWebServiceClient extends javax.xml.ws.Service {
// ...
private final QName portName = "...";
// ...
public RetrieveMyObjects getRetrieveMyObjects() {
return super.getPort(portName, RetrieveMyObject.class);
}
// ...
}
// generated port interface
// annotations here
public interface RetrieveMyObjects {
// annotations here
List<MyObject> getAll();
}
Now, upon executing following code:
MyWebServiceClient wsClient = new MyWebServiceClient("wsdl/location/url/here.wsdl");
RetrieveMyObjectsPort retrieveMyObjectsPort = wsClient.getRetrieveMyObjects();
wsClient should return instance which is both instance of RetrieveMyObjects & javax.xml.ws.BindingProvider interfaces. It is not stated anywhere on the surface of JAX-WS, but it seems that a lot of code is based on that fact. One can re-assure him\herself by executing something like:
if(!(retrieveMyObjectsPort instanceof javax.xml.ws.BindingProvider)) {
throw new RuntimeException("retrieveMyObjectsPort is not instance of " + BindingProvider.class + ". Redirect following as well as authentication is not possible");
}
Now, when we are sure that retrieveMyObjectsPort is instance of javax.xml.ws.BindingProvider we can send plain HTTP POST request to it, simulating SOAP request (though it looks incredibly incorrect & ugly, but this works in my case and I didn't find anything better while googling) and check whether web service will send redirect status as a response:
// defined somewhere before
private static void checkRedirect(final Logger logger, final BindingProvider bindingProvider) {
try {
final URL url = new URL((String) bindingProvider.getRequestContext().get(ENDPOINT_ADDRESS_PROPERTY));
logger.trace("Checking WS redirect: sending plain POST request to {}", url);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/html; charset='UTF-8'");
connection.setDoOutput(true);
if(connection.getResponseCode() == 307) {
final String redirectToUrl = connection.getHeaderField("location");
logger.trace("Checking WS redirect: setting new endpoint url, plain POST request was redirected with status {} to {}", connection.getResponseCode(), redirectToUrl);
bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, redirectToUrl);
}
} catch(final Exception e) {
logger.warn("Checking WS redirect: failed", e);
}
}
// somewhere at the application start
checkRedirect(logger, (BindingProvider) retrieveMyObjectsPort);
Now, what this method does is: it takes BindingProvider.ENDPOINT_ACCESS_PROPERTY of retrieveMyObjectsPort i.e. the url to which this port method will be sending SOAP requests and sends plain HTTP POST request as described above. Then it checks whether response status is 307 - Temporary Redirect (other statuses like 302 or 301 may also be included) and if it is, gets the URL to which web service is redirecting and sets new endpoint for the specified port.
In my case this checkRedirect method is called once for each web service port interface and then everything seems to work fine:
Redirect is checked on url like http://example.com:50678/restOfUrl
Web service redirects to url like https://example.com:43578/restOfUrl (please note that web service client authentication is present) - endpoint of a port is set to that url
Next web service requests executed via that port are successful
Disclaimer: I'm quite new to webservices and this is what I managed to achieve due to the lack of solutions for this questions, so please correct me if something is wrong here.
Hope this helps
Yes I know this post is old, but I've had similar errors, and thought maybe somebody would benefit from my solution.
the one that plagued me the most was:
com.sun.xml.ws.client.ClientTransportException: The server sent HTTP status code 200: OK
Which turns out to mean an incomplete response header. Apparently jax-ws does some kind of validation that includes validating the HTTP headers as well. And the server I was using was just sending an empty header.
It worked like a charm after adding 'application/soap+xml' to the Content-Type header.

Categories

Resources