posting form data with javaws in play - java

Hy,
I want to do calls to a different rest api from my play application. I'm using the javaws included library.
The specific call requires that I send form data. However I have no idea how I can send the correct data along with my request.
As far as I can see the library only supports sending url-encoded-form-data.
Does anyone know how I can send form-data along with my request like a normal website doing a form submission?
At the moment I have this:
Promise<WSResponse> promise = WS.url("http://localhost:"+port+"/login").setContentType("multipart/form-data").post("emailAddress=" + email +"&password=" + password);
Thanks,

Use application/x-www-form-urlencoded instead of multipart/form-data.
Promise<WSResponse> promise = WS.url("http://localhost:"+port+"/login")
.setContentType("application/x-www-form-urlencoded")
.post("emailAddress=" + email +"&password=" + password);

Related

Linebreak in AWS SNS through Api Gateway and Java

I am triggering the AWS SNS through the API Gateway.
JSONObject requestBody = new JSONObject();
requestBody.put("phone_number", receiverNumber);
requestBody.put("sender_id", senderAlias);
requestBody.put("message_text", messageText);
This JSONObject is being sent to the api gateway as a ByteArrayInputStream throug the AWS SDK for Java v1.
There are "\n" in the text, to create line breaks. The sms however does not have a new line there, it just prints \n.
In the Api Gateway the message is extracted like this: method.request.body.message_text
How do I have to set up the messageText variable to print new lines in the SMS? I tried replacing it with \n or \\n or \\\\n.. Also tried ASCII, didn't work.
Invocation
As this is a quite complex programm I can't show all of it. It's triggered via Insomnia with a String in Json format like this:
It has to be a double backslahed n because thats just how the code needs it. The aws integration is an additional provider so it has to fit in already existing frames. The json object looks like this before being executed.
So I need to find a way to manipulate the string thats going in the object. But I don't know how.
EDIT 3:
Deleting previous edits, as they were not helpful and did not target the problem as I know now.
Finally closing down the issue. It's a problem in the API-Gateway. The object reaches the gateway just fine, with a \n. Which would work in the SNS Service. But to trigger the SNS Service, it's all going into one URL, which converts the \n into %5Cn
Before transformation:
URL:
So the problem is in the URL encoding..
Thanks to the AWS Support I now am able to send SMS with line breaks through the api gateway.
It was wrong to use URL Query Parameters. I removed all of them
I needed one HTTP Header:
Content-Type: 'application/x-www-form-urlencoded'
Then I used a Messaging Template like this, with passthrough: Never:
#set($message = $input.path('$.message_text'))
#set($phoneNumber = $input.path('$.phone_number'))
Action=Publish&PhoneNumber=$util.urlEncode($phoneNumber)&Message=$util.urlEncode($message)&MessageAttributes.entry.1.Name=AWS.SNS.SMS.SenderID&MessageAttributes.entry.1.Value.DataType=String&MessageAttributes.entry.1.Value.StringValue=Alias
Having my JSON Object in the Request like this:
{
"phone_number": "+4912345678",
"message_text": "Break\nHere",
"sender_id":"Alias"
}
Works perfectly fine with a line break in the SMS

Graph REST API -- Reading Email (Java) -- NoPermissionsInAccessToken

The objective that I am after is that I would like to obtain an email from Outlook 365 without any human interaction.
So I am trying to use MS Graph REST API and Java.
To obtain the access token, I use:
resource=https://graph.microsoft.com
response = Unirest.post(
String.format("https://login.microsoftonline.com/%s/oauth2/token",
auth.getProperty("tenant_id")))
.header("Content-Type", "application/x-www-form-urlencoded")
.field("grant_type", "client_credentials")
.field("resource", auth.getProperty("resource"))
.field("client_id", auth.getProperty("app_id"))
.field("client_secret", auth.getProperty("app_secret"))
.asString();
which returns a string, which is parsed into a JSON, and passed into:
jsonNode = Unirest.get(
String.format("https://graph.microsoft.com/v1.0/users/%s/mailFolders",
prop.getProperty("user_email")))
.header("Accept", "application/json")
.header("Authorization", json.get("token_type") + " " + json.get("access_token"))
.asString();
I am getting the error with the message, "The token contains no permissions, or permissions can not be understood."
I do not have admin access to Azure AD, but I do have access to the user_mail inbox, which I can access through https://outlook.office365.com/mail/inbox.
I feel like I went off on a tangent, but not sure what else I can do.
Does anyone know what needs to be done to allow me to receive emails thru MS-Graph API? Or a better way of doing this?
Appreciate all the help I can get.
You would need to register an application in Azure AD in your tenant and provide the permissions that a user would require access to.
As you are trying to access
v1.0/users/%s/mailFolders
Looks like you want to use applicatoin permissions (not delegated permissions). So you would need to use Mail.ReadWrite application permissions which would require admin consent too.
You can use this tutorial to get an idea of how to connect Microsoft Graph using JAVA too https://learn.microsoft.com/en-us/graph/tutorials/java

Passing API Key, usr/pwd in httppost URL. is it permitted? txtwire API

I am trying to use txtwire (for sending SMS) and they provide a httppost service mentioned below. I know it is "https" but still.. is it OK to pass my API key, userName & Password in the URL?
There is no Basic Auth Mechanism because service expects everything in URL.
https://api.txtwire.com/httppost?phone=18885554433,18885554422&username={username}&password={password}&api_key={api_key}&code=12345&keyword={Group Keyword}&message=testMessage
My only other option is to user their SOAP web service. which is cumbersome and i would prefer RESTful. would SOAP be better if passing credentials in URL is not preferred?
Here is the API : https://api.txtwire.com/documentation/class_w_s___message.html#a99faeee5de80610649b184f180098982
will appreciate any help.
Is it permitted? Well, this is a question that API service provider should answer. It looks like that textWire API doesn't have any issue with it.
For the sake of security, personally, I don't like to post/get credentials without being encrypted. Even with Basic Authorization, there is a way to add encrypted username and password as request header "Authorization". Something similar to the following:
headers['Authorization'] = 'Basic '+ <encoded Base 64 String (username + password)>
Perhaps you want to find out if textWire API support such approach.
You should be ok for both of them, from what I can see they're using an SSL+TLS certificate.
From a more technical point of view, passing the password as part of the query string (RESTful), passing it in the request body (SOAP) or passing it as a request header is actually the same approach (don't forget that basic authentication trasmits the credentials as username:password sequence encoded with base64), because the password itself is being transmitted along with the message itself.
It's a possibile practice, but I would not raccomend it. If I were to expose an authenticated service I would use a username+HMAC signature combination, or maybe an autentication token of some sort.

How does cookies work, when calling cookie-setting REST services from java VM?

I'm in the process of learning how to use HP Quality Center's REST api to query and manipulate data. Unlike REST standard, this API is not completely stateless. It uses cookies to store authentication sessions.
I've tried to implement a very simple test, using the Jersey Client library. I can successfully authenticate my user, by sending my credentials. The API reference claims that this will set a cookie, and I am good to go with further calling the REST api. However, a simple "is-authenticated" call returns a 401, Authentication failed.
I have a feeling that the cookie writing or reading is not working properly, as everything else seems to work as it should. But I haven't been able to find out if or how cookies are set and read, when no browser is involved. So How does cookies work, when calling cookie-setting REST services from java VM? Does it work at all? Where are they stored?
I am using Eclipse Kepler as my IDE, if that matters at all, and a 32-bit java 1.6 JDK and JRE.
Code, and response strings below:
1. Logging in:
Client client = ClientBuilder.newClient();
Response response = client
.target("http://[host]:[port]").path("qcbin/authentication-
point/alm-authenticate")
.request().post(Entity.entity("<alm-authentication>
<user>username</user>
<password>secret</password></alm-authentication>",
MediaType.TEXT_XML_TYPE));
System.out.println(response.toString());
Output:
InboundJaxrsResponse{ClientResponse{method=POST,
uri=http://[host]:[port]/qcbin/authentication-point/alm-authenticate,
status=200, reason=OK}}
API Return description:
One of:
HTTP code 200 and sets the LWSSO cookie (LWSSO_COOKIE_KEY).
HTTP code 401 for non-authenticated request. Sends header
WWW-Authenticate: ALMAUTH
2. Verifying Logged in:
response = client.target("http://[host]:[port]")
.path("qcbin/rest/is-authenticated")
.request().get();
System.out.println(response.toString());
Output:
InboundJaxrsResponse{ClientResponse{method=GET,
uri=http://[host]:[port]/rest/is-authenticated, status=401,
reason=Authentication failed. Browser based integrations - to login append
'?login-form-required=y to the url you tried to access.}}
PS: adding the ?login-form-required=y to the URL, will bring up a log-in window when called in a browser, but not here. Appending the line to the URL actually still gives the same error message, and suggestion to append it again. Also, when called in a browser, the is-authenticated returns a 200, success, even without the login-form.
When you log in, you're getting a cookie which is a name plus a value.
The REST server expects you to pass this in the request header with every request you make.
Look into the object which you get for client.request(); there should be a way to specify additional headers to send to the server. The header name must be Cookie and the header value must be name=value.
So if the server responds with a cookie called sessionID with the value 1234, then you need something like:
client.request().header("Cookie", "sessionID=1234")
Related:
http://en.wikipedia.org/wiki/HTTP_cookie

How to detect the redirect to retrieve access_token via java

I'm starting to use facebook Graph API and I'm going to retrieve an access token with some simple HTTP requests via java.
Following https://developers.facebook.com/docs/authentication/
I created a new app but I don't have a domain so
I make an HTTP request to
www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&
redirect_uri=https://www.facebook.com/connect/login_success.html
for a server-side flow, and I suppose to get redirect to a success page with a code in the URL. Then I would use this code make another HTTP request to
graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&
client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE
and finally get my access token.
I used both java.net.HttpURLConnection and org.apache.http.HttpResponse,
but, in both cases, executing the first call I get as response the HTML of a Facebook login page.
If I use this HTML to create a webpage and then I simply click on the Login button (without inserting username and password) I get the success page with the code!
In the HTML the field submit of the button Login is empty and I can't retrieve redirect URLs... I can just read an alternate link in the <meta> tag which generate an auth_token (what is it? It is very different wrt an normal access_token...).
So what I ask is:
it is possible to detect the hidden redirect in some way just
using java.net.HttpURLConnection or
org.apache.http.HttpResponse?
if yes, how is the mechanism? Is it related to the auth_token?
if no, is it possible with other libraries? (I used also restfb,
but they seems to require an access token inserted "by hand" as an
arg, and I also saw facebook-java-api but it seems old).
Also if I'm logged in Facebook, executing the first HTTP call via Java I get as response the HTML of a Facebook login page.
Using HTML to create a webpage and then I simply click on the Login button (without inserting username and password) I get the success.htm page with the code parameter in the URL.
If I use the original URL directly in my browser I can directly obtain the success.htm page without passages in the middle.
So I suppose the problem is in the management of cookies: in Java (executed in Eclipse) I cannot access my browser's cookies.
I tried to redirect to use a Servlet but I get the error about the domain:
ServletURL is not a Facebook domain or a "site URL" registered for my app (actually I did't set a site URL for my app... and that's the problem core).
In any case here
http://developers.facebook.com/docs/authentication/
in the section App types > Desktop apps they say:
[...] After the user authorizes your app [I allowed everything], we
redirect the user back to the redirect_uri with the access token in
the URI fragment: [...]
Detect this redirect and then read the access token out of the URI
using whatever mechanisms provided by your framework of choice. [...]
So I think that it is still possible to detect this redirect via Java. How?
If you do not have a domain yet I recommend you using localhost as a domain. That way you can test it on your local web server / local app.
Using HttpURLConnection works fine.
This is how we do it.
Redirect to:
"https://graph.facebook.com/oauth/authorize?" +
"client_id=" + clientId + "&" +
"redirect_uri=" + URLEncoder.encode(returnUrl, "utf-8")
// After redirect to the return url do the following:
//Make a http request to
"https://graph.facebook.com/oauth/access_token?client_id=" +
"client_id=" + clientId + "&" +
"redirect_uri=" + URLEncoder.encode(returnUrl, "utf-8") + "&"+
"client_secret=" + clientSecret + "&"+
"code=" + request.getParameter("code");
This will return an access token which you can query facebook with

Categories

Resources