WSO2 token generation using Token API failing - wso2

I am using WSO2-AM-1.9.0, trying to generate the Access token using Consumer Key and Consumer Secrete.
When making a call using CURL it works fine
curl -k -d "grant_type=password&username=testuser1&password=testUser1&scope=SANDBOX" -H "Content-Type:application/x-www-form-urlencoded" -H "Authorization:Basic ZXNuaHJTZmJmOW9XS28xTVM5UHJSZ1BacUU0YTpld040RGh1ZmsxYTNZbndVNU1uMVlGM3IwanNh" http://10.0.100.108:8280/token
But when trying with Java it returns 403 error code. Code is:
try
{
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://10.0.100.108:8280/token");
HttpParams params=new BasicHttpParams();
get.addHeader("Authorization","Basic ZXNuaHJTZmJmOW9XS28xTVM5UHJSZ1BacUU0YTpld040RGh1ZmsxYTNZbndVNU1uMVlGM3IwanNh");
get.addHeader("content-type", "application/x-www-form-urlencoded");
params.setParameter("grant_type", "password");
params.setParameter("username", "testuser1");
params.setParameter("password", "testUser1");
params.setParameter("scope", "SANDBOX");
get.setParams(params);
HttpResponse response = client.execute(get);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
responseBody = responseBody +"\n"+line;
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
Error:
403 Status report
Runtime Error No matching resource found in the API for the given request
Any help and info on this is appreciated.

You have to send a POST request not a GET. Use,
HttpPost httpPost = new HttpPost("http://10.0.100.108:8280/token");

Related

Calling the rest video intelligence API in JAVA

I've been trying to call the rest API of video intelligence through a java program to annotate a local file. Here is my code:
byte[] data = Files.readAllBytes(path);
byte[] encodedBytes = Base64.encodeBase64(data);
URIBuilder builder = new URIBuilder("https://videointelligence.googleapis.com/v1beta2/videos:annotate");
URI uri = builder.build();
HttpPost request = new HttpPost(uri);
request.setHeader("Content-Type", "application/json");
request.setHeader("X-Goog-Api-Key",MyKey);
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonArray.put("LABEL_DETECTION");
json.put("inputContent", encodedBytes);
json.put("features", jsonArray);
StringEntity reqEntity = new StringEntity(json.toString());
request.setEntity(reqEntity);
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
I'm getting this error:
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"input_content\": Proto field is not repeating, cannot start list.
Could anyone help me with this error please? thank you
The error message is not really helpful. Problem here is that "inputContent" should be String instead of byte[]. This worked for me:
String str = new String(encodedBytes, "UTF-8");
requestJson.put("inputContent", str);

connection.getConnetion() returns 404 code on WebSphere7

I have implemented a REST service using Spring Integration.
When I try to access the service manually using main function, It is working fine.
I also tested the service using REST Client in Google Chrome and that worked. But the service is coming back with responseCode 404 on WebSphere server. So I am facing the issue when I deploy the code on higher environment.
URL u = new URL("http://localhost:8080/MyApplication/testRestService");
URLConnection uc = u.openConnection();
HttpURLConnection connection = (HttpURLConnection) uc;
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept","*/*");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = connection.getOutputStream();
Writer wout = new OutputStreamWriter(out);
//helper function that gets a string from a dom Document
String input = jsonInput;
wout.write(input.getBytes());
wout.flush();
wout.close();
// Response
int responseCode = connection.getResponseCode();
Is is dependent on server, so its coming back with response code 404 ? Do we need any server side configuration ?
Any suggestion will be appreciated.
Why do you use different ContentType for URLConnection and for httpClient?
Show, please, your REST service config: 404 means Not found. Therefore you use (or don't) some options in request which makes it non-matching for the server's RequestMapping.
I tried with Apache HTTP Client and the code is working on WebSphere now. Still I am not able to find the reason why java.net.HttpURLConnection was not working on WebSphere.
Please find my updated code below :
DefaultHttpClient httpClient = null;
HttpPost postRequest = null;
StringEntity inputEntity = null;
HttpResponse response = null;
try{
//RETREIVE WEB SERVICE URL FROM DB
String callbackURL = "http://localhost:8080/MyApplication/testRestService";
httpClient = new DefaultHttpClient();
postRequest = new HttpPost(callbackURL);
String inputData = request.toString();
inputEntity = new StringEntity(inputData);
inputEntity.setContentType("application/x-www-form-urlencoded");
postRequest.setEntity(inputEntity);
response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 201 && response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "+ response.getStatusLine().getStatusCode());
}
//System.out.println("HTTP Response Code :"+response.getStatusLine().getStatusCode());
LOGGER.debug("HTTP Response Code :"+response.getStatusLine().getStatusCode());
httpClient.getConnectionManager().shutdown();
}catch(IOException ex){
ex.printStackTrace();
throw ex;
}finally{
httpClient.getConnectionManager().shutdown();
httpClient = null;
postRequest = null;
inputEntity = null;
response = null;
}

How to send http get request to servlet from restful webservice?

I am beginner in that, but
I have a restful web service and i want to send a http get request from it and handle the response in it. if any one knows how can i do this ?
i tried this :
#Context private HttpServletRequest servletRequest;
#Context private HttpServletContext servletContext;
but i want to know what's this injection will return to me? i don't understand how will get it and it's scope, and how to get the response?!
and how i will send the request?
i found this http client apache
and here is an example for sending an Get request and getting the response
http://www.mkyong.com/java/apache-httpclient-examples/
String url = "http://www.google.com/search?q=httpClient";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
i'll try and post any helpful edits i reach, anyone have another helpfull comments or edits please do.

Kerberos Authentication header for JAX-WS client

I am generating my web service using ws-import to connect to an aspx service that I have secured with Kerberos on IIS.
I am able to connect and authenticate fine when I just connect to the service using a SOAPConnection
final SOAPConnection conn = SOAPConnectionFactory.newInstance().createConnection();
try {
final MessageFactory msgFactory = MessageFactory.newInstance();
final SOAPMessage message = msgFactory.createMessage();
final MimeHeaders headers = message.getMimeHeaders();
if (spnegoToken != null) {
headers.addHeader("SOAPAction", "http://tempuri.org/HelloWorld");
headers.addHeader("Authorization", "Negotiate " + Base64.encode(spnegoToken));
}
message.getSOAPBody().addBodyElement(new QName("http://tempuri.org/", "HelloWorld", "tem"));
final SOAPMessage response = conn.call(
message, "http://server:9994/WebService/SampleService.asmx");
return response.getSOAPBody().getTextContent();
} finally {
conn.close();
}
However I am unable to add an Authorization header to the JAXWS generated WS in the same way:
final SampleServiceSoap sss= new SampleService().getSampleServiceSoap();
((BindingProvider) sss).getRequestContext().put(
"Authorization", "Negotiate " + Base64.encode(spnegoToken));
return sss.helloWorld();
I get a 401 error as the token as I cannot see the token attached in Wireshark.
Can anyone point me at the approach I should take?
Cheers,
Barry
Sorted, turns out I was pretty close:
final Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("Authorization", Collections.singletonList("Negotiate " + Base64.encode(tgt)));
((BindingProvider) sss).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, headers);

API Manager OAuth Token Revoke is Problematic

I am using SAML2 Bearer assertion profile to obtain OAuth Tokens form WSO2 API Manager. I have two client applications. In the OAuth Token Revoking process I am using following code,
public static boolean revokeToken(Token token) throws IOException {
//Create connection to the Token endpoint of API manger
URL url = new URL(Config.apiMangerOAuthRevokeURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
String userCredentials = Config.apiMangerClientID+":"+ Config.apiMangerClientSecret;
String basicAuth = "Basic " + new String(Base64.encodeBytes(userCredentials.getBytes()));
basicAuth = basicAuth.replaceAll("\\r|\\n", "");
// Set the consumer-key and Consumer-secret
connection.setRequestProperty("Authorization", basicAuth);
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes("token="+token.getAccess_token());
wr.flush();
wr.close();
//Get Response
InputStream iss = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(iss));
String line;
StringBuffer responseString = new StringBuffer();
while ((line = rd.readLine()) != null) {
responseString.append(line);
responseString.append('\r');
}
rd.close();
System.out.println("Revoking Token Mobile-"+token.getAccess_token());
System.out.println("Revoking Response Mobile -"+responseString.toString());
return true
;
}
One client application do the revoking process OK. I tried to invoke API using CURL after revoking, it fails as expected. But the other client application which use same above logic to revoke tokens return well. But the token is valid after revoking. I can use CURL to query the API. What has gone wrong here?
API Manager has caching enabled by default and is set to 15 min. Try disabling it.