Rewriting curl http request using Groovy - http

Here is my test HTTP request I need to rewrite to use in groovy:
curl 'https://api-dev.test.ru/uaa/oauth/token' -H 'Authorization: Basic 1234567=' -H 'Content-Type: application/x-www-form- urlencoded' -H 'Accept: application/json, text/plain, */*' --data 'grant_type=password' --data-urlencode 'username=theLogin' --data-urlencode 'password=thePassword'
Here is the way I've rewritten it:
def httpRequest = [path : 'https://api-dev.test.ru/uaa/oauth/token',
headers : ['Authorization: Basic 1234567='
'Content-Type': 'application/x-www-form-urlencoded',
'Accept' : 'application/json, text/plain, */*'],
data : ['grant_type=password'],
data_urlencode: ['username=theLogin',
'password=thePassword']
]
It seems to be not correctly, because the test app doesn't work with the request. Have I rewritten the request correctly. If I haven't, where is my mistake?

You should be using Http Builder. Your code would look like:
def result = HttpBuilder,configure {
request.uri = 'https://api-dev.test.ru/uaa/oauth/token'
request.contentType = 'application/x-www-form-urlencoded'
request.headers.Accept = 'application/json, text/plain, */*'
}.post {
request.auth.basic 'admin', 'myp#$$w0rd'
request.uri.query = [ grant_type:'password' ]
request.body = [username:'theLogin', password:'thePassword']
}

Related

How to send a cookie in DRF-Spectacular Authorization?

I have written a custom backend for JWT authentication in cookies. I'd like to test it using the DRF-Spectacular. To this end, I've written the following scheme:
from drf_spectacular.extensions import OpenApiAuthenticationExtension
from .backends import JWTCookieAuthentication
class JWTCookieAuthenticationScheme(OpenApiAuthenticationExtension):
name = "JWTCookieAuthenticationScheme"
target_class = JWTCookieAuthentication
def get_security_definition(self, auto_schema):
return {
'type': 'apiKey',
'in': 'cookie',
'name': 'jwt',
}
The "Authorize" button appears in the generated API, but the entered value is passed in the header instead of the cookie. The generated CURL command for an exemplary request is the following:
curl -X 'GET'
'http://localhost:8001/user/my_user/'
-H 'accept: application/json'
-H 'Cookie: jwt=12345'
while the expected one would be something like:
curl -X 'GET'
'http://localhost:8001/user/my_user/'
-H 'accept: application/json'
--cookie 'jwt=12345'
Is it a bug or I'm doing something wrong?

How to connect an API to R Studio

I'm trying to connect the API to my r studio. After executing the below code I got the error 403. Access Denied due to Invalid Authorization.
apiKey <- "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6IjI4YTMxOGY3LTAwMDAtYTFlYi03ZmExLTJjNzQzM2M2Y2NhNSJ9.eyJpc3MiOiJzdXBlcmNlbGwiLCJhdWQiOiJzdXBlcmNlbGw6Z2FtZWFwaSIsImp0aSI6ImQ2YzliYjRmLTIwZmMtNDc3NS1iMTYxLWNmMzgzZWMyYThmYSIsImlhdCI6MTYzODgzMDY2Miwic3ViIjoiZGV2ZWxvcGVyLzU1M2E1ODA1LTA1YzctNTQyZS00MjAyLTY4NjNkYjZmYjg0OCIsInNjb3BlcyI6WyJicmF3bHN0YXJzIl0sImxpbWl0cyI6W3sidGllciI6ImRldmVsb3Blci9zaWx2ZXIiLCJ0eXBlIjoidGhyb3R0bGluZyJ9LHsiY2lkcnMiOlsiODQuODIuMjA5LjMiXSwidHlwZSI6ImNsaWVudCJ9XX0.lUSKahV0RJR23NHQmEQJopkp31qwD3VcGqr8gBVTIEt0Hg3cK4AMg00kGVD9NFqXhUmnEOeQtLug2ZJcsXCYbQ"
url <- "https://api.brawlstars.com/v1/players/%238QUYQ8/battlelog"
headers <- c('Content-type' = 'application/json',
'Accept' = 'application/json',
'authorization' = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6IjI4YTMxOGY3LTAwMDAtYTFlYi03ZmExLTJjNzQzM2M2Y2NhNSJ9.eyJpc3MiOiJzdXBlcmNlbGwiLCJhdWQiOiJzdXBlcmNlbGw6Z2FtZWFwaSIsImp0aSI6ImQ2YzliYjRmLTIwZmMtNDc3NS1iMTYxLWNmMzgzZWMyYThmYSIsImlhdCI6MTYzODgzMDY2Miwic3ViIjoiZGV2ZWxvcGVyLzU1M2E1ODA1LTA1YzctNTQyZS00MjAyLTY4NjNkYjZmYjg0OCIsInNjb3BlcyI6WyJicmF3bHN0YXJzIl0sImxpbWl0cyI6W3sidGllciI6ImRldmVsb3Blci9zaWx2ZXIiLCJ0eXBlIjoidGhyb3R0bGluZyJ9LHsiY2lkcnMiOlsiODQuODIuMjA5LjMiXSwidHlwZSI6ImNsaWVudCJ9XX0.lUSKahV0RJR23NHQmEQJopkp31qwD3VcGqr8gBVTIEt0Hg3cK4AMg00kGVD9NFqXhUmnEOeQtLug2ZJcsXCYbQ')
The curl code is working well. Here below is the curl code:
curl -X GET --header 'Accept: application/json' --header "authorization: Bearer <API token>" 'https://api.brawlstars.com/v1/players/%238QUYQ8/battlelog'

Multiple Authentication in CURL

Context
I want to access an API from R and have the correct credentials to do so.
The issue is that Authentication requires three arguments to be passed (Username, Password and Organisation).
I am not familiar with API calls from R and I do not know how to pass this "organisation" argument.
Example
An example of the API call to request a token is as follows (taken from the documentation):
curl -X POST "https://URL.com" \
-H "Content-Type: application/json" \
--data "{\"user_name\": \"<username>\" \
\"password\": \"<mypassword>\",\
\"organisation\": \"<organisation>\"}"
Using the crul package, I have tried:
require("crul")
z <- crul::HttpClient$new(url = "https://THEURL.com",
auth(user = "myuser",
pwd = "mypwd"))
z$get()
Which returns:
<crul response>
url: https://THEURL.com
request_headers:
User-Agent: libcurl/7.59.0 r-curl/3.3 crul/0.8.0
Accept-Encoding: gzip, deflate
Accept: application/json, text/xml, application/xml, */*
response_headers:
status: HTTP/1.1 403 Forbidden
content-type: application/json
content-length: 211
connection: keep-alive
x-amzn-errortype: IncompleteSignatureException
Im assuming that x-amzn-errortype is referring to the missing organisation authentication variable.
Questions
How can I pass the variable "Organisation" to the function?
Or is there a better way to do this?
I think it will be way easier for you to use the package httr when you deal with HTTP requests. I think your example request could be:
library(httr)
POST("https://THEURL.com",
body = list(user_name = "<username>", password = "<mypassword>", organisation = "<organisation>"),
encode = "json")

Bad request returned when using the DELETE curl method with Guzzle and sendgrid

I'm trying to use the sendgrid v3 API to purge bounces, it works fine when using CURL in CLI, here is the command:
curl -v -X DELETE -d '{"delete_all": true}' -H "Content-Type: application/json" -H "Authorization: Bearer SG.mykey" "https://api.sendgrid.com/v3/suppression/bounces"
But when trying to launch it with Symfony2 / Guzzle, I am getting a bad request error, however the request seems OK, here is the output of (string) $request:
"""
DELETE /v3/suppression/bounces HTTP/1.1\r\n
Host: api.sendgrid.com\r\n
Authorization: Bearer SG.mykey\r\n
User-Agent: Guzzle/3.9.3 curl/7.35.0 PHP/5.5.9-1ubuntu4.17\r\n
Accept: application/json\r\n
Content-Length: 20\r\n
\r\n
{"delete_all": true}
"""
And the exception:
[Guzzle\Http\Exception\ClientErrorResponseException]
Client error response
[status code] 400
[reason phrase] BAD REQUEST
[url] https://api.sendgrid.com/v3/suppression/bounces
When using the GET method, it works correctly and it returns me all the bounces.
Here is the guzzle code:
$request = $this->httpClient->delete('/v3/suppression/bounces', null, '{"delete_all": true}');
$response = $request->send();
The http client is a service initialized with the https://api.sendgrid.com base URL.
Your problem I think is that you are sending 3 params to delete when it only has two, instead what you need to do is pass the body in options array.
$response = $this->httpClient->delete(
'/v3/suppression/bounces',
[
'body' => json_encode(['delete_all', true]),
'Authorization' => 'Basic ' . base64_encode($username . ':' . $password),
'content-type' => 'application/json'
]
);
Guzzle options docs
Answering to myself. The problem was pretty obvious: The content-type header was not set, the "accept" one was. I didn't care about this header because you don't have to pass it when using the GET method for this API. So now when debugging my request object I have:
"""
DELETE /v3/suppression/bounces HTTP/1.1\r\n
Host: api.sendgrid.com\r\n
Authorization: Bearer SG.mykey\r\n
Content-Type: application/json\r\n
Content-Length: 20\r\n
User-Agent: Guzzle/3.9.3 curl/7.35.0 PHP/5.5.9-1ubuntu4.17\r\n
Accept: application/json\r\n
\r\n
{"delete_all": true}
"""

PUT request using `UrlFetchApp` returns 'Bad Request' but the same request outside Google Apps Script works

This is the Google Apps Script that makes the request:
UrlFetchApp.fetch('https://user:password#sitename.com/api', {
method: 'put',
headers: { 'Accept': '*/*' },
payload: 'foo=bar&baz=qux'
});
Which can be successfully posted to http://requestb.in/, for examination:
PUT /1bfk94g1 HTTP/1.1
User-Agent: Mozilla/5.0 (compatible; GoogleDocs; script; +http://docs.google.com)
Host: requestb.in
Content-Type: application/x-www-form-urlencoded
Content-Length: 43
Connection: keep-alive
Accept-Encoding: gzip
Accept: */*
foo=bar&baz=qux
But fails when the request URL is https://user:password#sitename.com/api. The only error information shown is Bad request: https://user:password#sitename.com/api.
I've constructed a curl command which yields the exact same HTTP request:
curl -XPUT \
-H 'Accept-Encoding: gzip' \
--user-agent 'Mozilla/5.0 (compatible; GoogleDocs; script; +http://docs.google.com)' \
-d foo='bar' \
-d baz='qux'\
https://user:password#sitename.com/api
Which successfully posts to https://user:password#sitename.com/api. How can two identical requests have different outcomes? Am I missing something with regards to my Google Apps Script? I've tried using the debugger, but it didn't help.
It appears that UrlFetchApp doesn't yet support requests with credentials in the URL. The Authorization HTTP header needs to be built manually. The following works:
var response = UrlFetchApp.fetch('https://sitename.com/api', {
headers: {
'Authorization': 'Basic ' + Utilities.base64Encode(user + ':' + password)
}
});

Resources