Groovy Rest/HTTP Request Native for use with Script Runner - rest

I am trying to build a simple Http Get request that requires me to submit an api key as authentication (api key as unsername and blank password). I have seen some solutions using the groovyx.net.http.HTTPBuilder library. However, the piece of code will need to be deployed in an evironment that does not allow for libraries. So I tried the following where is the url of the website i am trying to reach:
// GET
def get = new URL("<url>").openConnection();
def getRC = get.getResponseCode();
println(getRC);
if(getRC.equals(200)) {
println(get.getInputStream().getText());
}
As expected this returns error 400 since I do not include any authentication with the api key, so I tried the following where is the api key:
def get = new URL("<url>");
def authString = "<api_key>:".getBytes().encodeBase64().toString();
def conn = get.openConnection();
conn.setRequestProperty("Authorization", "Basic ${authString}");
def getRC = conn.getResponseCode();
println(getRC);
println(conn.getInputStream().getText());
But I still get the 400 error. I tried picking up the request through Fiddler but it doesn't seem to be tracking it (executing Groovy code through GroovyConsole).

The second approach works. My mistake was to not substitute spaces in the URL with % signs.

Related

getting url parameters in tornado

i've been facing some problems in getting url parameters using Tornado web framework.
these are my codes:
def main_app():
return tornado.web.Application([
(r"/reg", register),
(r"/account", account),
])
class account(tornado.web.RequestHandler):
def get(self):
name = self.get_argument('name')
depo = self.get_argument('depo')
respone = {'name':name ,'depo':depo}
self.write(respone)
i've tried to use some restful API to test this web service.
i curl a url like curl localhost:8000/account?name = "parsa" & depo = "10"
but always i get this error that says it doesn't recognize depo. actually i tested something and it showed that each time the second parameter doesn't work well or even the third one doesn't work.
i tried several ways but didn't work.
This is not a problem with your Tornado code. You are making the curl request incorrectly. You can verify that by visiting that url from your browser.
With, curl, you'll have to wrap the whole url in quotes:
curl "localhost:8000/account?name=para&depo=10"

Play WS OAuth content length required

I am having trouble connecting to the Evernote API using the OAuth wrapper bundled with Play 2.6.10 WS.
I am currently using sbt 0.13.15, Oracle JDK 1.8, and Scala 2.12.3.
The relevant piece of code from my OAuth Play controller:
import play.api.libs.oauth._
val KEY = ConsumerKey("KEY", "SECRET")
val EVERNOTE = OAuth(
ServiceInfo(
"https://sandbox.evernote.com/oauth",
"https://sandbox.evernote.com/oauth",
"https://sandbox.evernote.com/OAuth.action",
key = KEY
),
use10a = false
)
// Step 1: Request temporary token
EVERNOTE.retrieveRequestToken(CALLBACK_URL) match {
case Right(t: RequestToken) =>
// Step 2: Request user authorization; pass temporary token from Step 1
// Also, store temporary token and secret for later use
Redirect(EVERNOTE.redirectUrl(t.token)).withSession("token" -> t.token, "secret" -> t.secret)
// TODO: check this out!
case Left(e) => throw e
}
The application crashes due to the exception thrown from the Either returned by retrieveRequestToken. The exact exception is:
OAuthCommunicationException: Communication with the service provider failed: Service provider responded in error: 411 (Length Required)
After some snooping around, it seems as if this issue is common in OAuth and requires the POST request headers to contain a Content-Length (typically set to 0). Example: Why I get 411 Length required error?. But as far as I can tell, Play WS does not expose this option from Signpost (OAuth library under the hood), so I was not able to try this solution.
Of course, I may be overlooking something here. Has anyone experienced a similar issue? I just want to make sure before creating a new issue on the WS repo.
Thanks.
Evernote requires content-length for the API calls so I think that's the case.
Getting 411 error bad request in Evernote

Using Proxy Authorization Header with ScalajHTTP

I'm getting a 407 error using scalajHTTP. I read through the repository and it seems like I should be able to pass the basic auth credentials as a base64 encoded value. I've also tried using the helper method described in the GitHub issues .proxyAuth but that is no longer part of HTTPRequest in ScalaJ according to error messages (as well as it not being in the documentation)
Any ideas? My endpoint URL is HTTPS as well as my proxy (for additional context)
val proxyHost= s"https://$forwardProxy"
val requestForward = Http(url).postData(redactedSecret)
.option(HttpOptions.allowUnsafeSSL)
.headers(("Content-Type", "application/json"), ("Proxy-Authorization", s"Basic $proxyAuth"))
.proxy(proxyHost, 8080).asString
val responseForward: HttpResponse[String] = requestForward
This issued posted in Github but still not resolved, https://github.com/scalaj/scalaj-http/issues/87
I found a solution to this problem. I researched around and after trying http client libraries, I kept getting 407 errors even though they all support proxy auth. Anyway, I ended up having to do the following.
add
import java.net.{Authenticator,PasswordAuthentication}
and the modified code body that I previously above looks like:
val requestForward: HttpRequest = Http(url).postData(data)
.header("Content-Type", "application/json")
.proxy(proxyHost, 8080)
.option(HttpOptions.allowUnsafeSSL)
Authenticator.setDefault(new Authenticator() {
override def getPasswordAuthentication(): PasswordAuthentication = {
new PasswordAuthentication( s"$username", s"$password".toCharArray())
}
})
So as you can see I removed the header from the original request object and instead overrode the credentials. Make sure you do this before you call on the response object.

Scala Play session always empty

I am trying to create a basic web login/authentication system in Play. Based on Play docs Im supposed to persist data across requests through Play's Session cookie; this is what my login looks like:
def login() = Action.async(parse.json) { implicit request =>
implicit val loginInfoReads: Reads[LoginInfo] = Json.reads[LoginInfo]
val newSession = request.session +
("test" -> "yep")
// #todo: add real error handling
val unauthedUser = request.body.validate(loginInfoReads)
.getOrElse(throw new Exception("Something went wrong with the login request"))
UserService.authAndGetUser(unauthedUser.email, unauthedUser.password).map { res =>
Ok(res.name).withSession(newSession)
}
I can see the cookie included in the response cookies in Chrome dev tools, but when I make a subsequent request to get the data inside the session, I get an empty map:
Logger.debug(request.session.data.toString)
logs:
Map()
and attempting to access "test" via request.session.get("test") fails.
What am I missing here? Why is my session data not persisting across requests?
Thanks
Turned out it wasn't a Scala/Play problem, more general problem with Chrome and cookies when hitting localhost. Here's what fixed it for me:
https://stackoverflow.com/a/39233628/747340

Grails REST plugin using HTTPBuilder for HTTPS

I have a service method in grails that was working fine.
It pulls a JSON via a GET request. After moving to prod we had to change the protocol to HTTPS and now I am getting an exception.
Is there anything I have to change to use the HTTPS protocol? I look all over The HTTPBuilder Documentation and I could not find a single reference to using HTTPS. I also could not find a example on Google.
def reportList = new ArrayList()
def result
//TODO Dynamic PatientKey
def http = new HTTPBuilder( 'https://mydomain/servicename?key=' + key )
reportList = null
http.request( GET, JSON ) { req ->
headers.Accept = 'application/json'
response.success = { resp, reader ->
reportList = reader.getAt("patientReports")
}
}
}
[ reportList : reportList ]
Whats the exception you are getting?
please check that SSL certificate is valid for the website. More here.
http://groovy.codehaus.org/modules/http-builder/doc/ssl.html
This Grails plugin solution works well in a test or local env because Same-Origin Policy will prevent you from implementing a front-end jQuery AJAX call since the domains are different.
In Prod, since HTTPS was used, and since the domains are the same, a jQuery AJAX call works much better then having the logic in the controller and using the REST plugin.
$.getJSON('${YOUR_URL}', function(data){ var yourData = data.yourData; //Operate on data here });