I'm doing a test via "test_client" and testing the "/me" endpoint which redirects, depending on the incoming token, to the secure endpoint either /users/user_id or /operators/operator_id. But after redirection headers become None`.
If I doing it via swagger - all works correctly, if I doing this via curl - I'm don't getting an answer at all.
So, the main problem is that headers are becoming are empty (no token) after redirection.
There is my code:
#app.api_route(path="/me",
status_code=308,
methods=["GET", "DELETE", "PATCH"],
tags=['me'],)
def get_my_profile(request: fastapi.Request, token: str = fastapi.Depends(config.oauth2_scheme), ):
token_payload = services_get_token_payload(token=token)
if token_payload['role'] == config.USER_ROLE:
url = f"{request.url.scheme}://{config.APP_IP}:{config.APP_PORT}/users/{token_payload['sub']}"
elif token_payload['role'] == config.OPERATOR_ROLE:
url = f"{request.url.scheme}://{config.APP_IP}:{config.APP_PORT}/operators/{token_payload['sub']}"
elif token_payload['role'] == config.EMPLOYEE_ROLE:
url = f"{request.url.scheme}://{config.APP_IP}:{config.APP_PORT}/employees/{token_payload['sub']}"
else:
raise fastapi.HTTPException('Can not redirect, some error occurred')
return fastapi.responses.RedirectResponse(url=url, status_code=308, headers=request.headers) # No matter `request.headers` or `dict(request.headers)`
#router.get(path="/{user_id}", status_code=200, response_model=schemas.UserOut)
async def get_user(
user_id: int = Path(default=...),
token: str = Depends(config.oauth2_scheme), # error during checking, no headers
postgres_session: AsyncSession = Depends(database.get_db),):
token_payload = services.get_token_payload(token=token)
services.verify_access(role=token_payload["role"], true_conds=token_payload['sub'] == user_id)
user = await crud.read_user(statement=users.select().where(users.c.id == user_id), db_session=postgres_session)
return schemas.UserOut(**user)
Proof with curl:
david#david-ThinkPad-E480:~$ curl -X 'GET' \
> 'http://127.0.0.1:8000/me' \
> -H 'accept: */*' \
> -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2IiwiZXhwIjoxNjIyNjc3NzgwLCJyb2xlIjoxLCJjaGF0X3Rva2VuIjp7ImlkZW50aXR5Ijo2LCJ0b2tlbiI6ImV5SjBlWEFpT2lKS1YxUWlMQ0poYkdjaU9pSklVekkxTmlJc0ltTjBlU0k2SW5SM2FXeHBieTFtY0dFN2RqMHhJbjAuZXlKcWRHa2lPaUpUU3pWaFpEVXpZV1UzTWpnek1XWTJORGRoWm1RNU1qQmlabUl6TW1Gak1XRTBMVEUyTWpFMU9UYzNPREFpTENKbmNtRnVkSE1pT25zaWRtbGtaVzhpT250OUxDSmphR0YwSWpwN0luTmxjblpwWTJWZmMybGtJam9pU1ZNelkyVTFNR1l3TnpnNE9HWTBaV1ZrT1dJM05ESXpZMlExWTJaa01EbG1OQ0o5TENKcFpHVnVkR2wwZVNJNk5uMHNJbWx6Y3lJNklsTkxOV0ZrTlROaFpUY3lPRE14WmpZME4yRm1aRGt5TUdKbVlqTXlZV014WVRRaUxDSmxlSEFpT2pFMk1qRTJNREV6T0RBc0ltNWlaaUk2TVRZeU1UVTVOemM0TUN3aWMzVmlJam9pUVVObU9ESTNORFJrTkRCbVlUTmxNbUZpTlRkbU56WTBOREV4TmpCaU5UUmlaQ0o5LnBzeVpJbE9OeTRRX2pNeHNnREswUUI2X3l4T20xcUZ6eVEyajczSHVvaWMifX0.c66ACoJpTLRXYMeysEYwUIQJSqIMEXegXRn4vc0sIMw'
david#david-ThinkPad-E480:~$
Related
I am trying to get data from an API with a POST request. The request works well with a direct shell command :
system(sprintf('curl POST -k --tlsv1.2 -v "https://api-gateway.inpi.fr/services/apidiffusion/api/marques/search" -H "X-XSRF-TOKEN: %s" -H \'accept: application/xml\' -H "Content-Type: application/json" -H "Cookie: XSRF-TOKEN=%s; access_token=%s; session_token=%s" -d \'%s\' > test.xml',token,token,access_token,refresh_token,json_request))
However, I would like to use httr for many reasons. I use the following code :
test <- httr::POST(
"https://api-gateway.inpi.fr/services/apidiffusion/api/marques/search",
httr::set_config(config(ssl_verifypeer = 0L)),
config = (add_headers(
"X-XSRF-TOKEN" = token,
"accept" = "application/xml",
"Content-Type" = "application/json",
"Cookie" = sprintf("XSRF-TOKEN=%s; access_token=%s; session_token=%s",token,access_token,refresh_token)
))
,set_cookies(`X-XSRF-TOKEN` = token,
`XSRF-TOKEN` = token,
access_token = access_token,
session_token = refresh_token)
,body = json_request
)
But this returns a 403 Forbidden error (my_token being the token I use) :
$error
[1] "access_denied"
$error_description
[1] "Invalid CSRF Token '*my_token*' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.
It seems like httr did not take into account my cookies because the token is different inside the test object I create :
> test2$cookies
domain flag path secure expiration name value
1 api-gateway.inpi.fr FALSE / FALSE <NA> XSRF-TOKEN *another_token*
Any idea ? I am sorry that I can't create a reproducible example for obvious security reasons.
Thank you !
The solution was wierd.
I had to rid off from httr, I used UNIX system commands instead, and it worked with the same request.
system(sprintf('curl POST -k --tlsv1.2 "https://api-gateway.inpi.fr/services/apidiffusion/api/marques/search" -H "X-XSRF-TOKEN: %s" -H \'accept: application/json\' -H "Content-Type: application/json" -H "Cookie: XSRF-TOKEN=%s; access_token=%s; session_token=%s" -d \'%s\' > %s/res.json',tokens$xsrf_token,tokens$xsrf_token,tokens$access_token,tokens$refresh_token,json_request,tempdir()))
It seems like httr tries to handle cookies by its own, so maybe that's what caused my problem.
I am trying to write a script to move repos in a project to another project but I am getting a 400 error whenever I try.
My python requests line looks like:
url = 'https://bitbucketserver.com/rest/api/1.0/projects/example1/repos/repo1'
token = 'TokenString'
response = requests.put(url, headers={'Content-Type': 'application/json', 'Authorization': 'Bearer' + token}, data={'project': {'key': 'NEW_PROJECT'}}, verify=False)
I get a response 400 that says 'Unexpected character ('p' (code112)): expected a valid value (number, string, array, object, true, false, or null) at [Source: com.atlassian.stash.internal.web.util.web.CountingServletInputStream#7ccd7631; line 1, column 2]
I'm not sure where my syntax is wrong
Not python, but work for me via curl:
curl -u 'USER:PASSWORD' --request PUT \
--url 'https://stash.vsegda.da/rest/api/1.0/projects/OLD_PROJECT/repos/REPO_TO_MOVE' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data '{
"project": {"key":"NEW_PROJECT"}
}'
Maybe can someone help.
I am trying to access the Amadeus travel API
To obtain a token, the given curl is:
curl "https://test.api.amadeus.com/v1/security/oauth2/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}"
My RScript Attempt is:
library("httr")
# Get Token
response <- POST("https://test.api.amadeus.com/v1/security/oauth2/token",
add_headers("Content-Type" = "application/x-www-form-urlencoded"),
body = list(
"grant_type" = "client_credentials",
"client_id" = API_KEY,
"client_secret" = API_SECRET),
encode = "json")
response
rsp_content <- content(response, as = "parsed", type = "application/json")
rsp_content
Resulting in the error:
Response [https://test.api.amadeus.com/v1/security/oauth2/token]
Date: 2021-07-23 00:59
Status: 400
Content-Type: application/json
Size: 217 B
{
"error":"invalid_request",
"error_description": "Mandatory grant_type form parameter missing",
"code": 38187,
"title": "Invalid parameters"
}
>
What is the correct way to call this API to obtain a token using R?
The curl -d option is used to send data in the same way an HTML form would. To match that format, use encode="form" rather than encode="json" in the call to POST().
I am trying to use the transaction email service MailerSend to send an email from R.
They have cURL instructions as to how to do this.
I don't think I have the formatting quite right as I get the error:
> response
Response [https://api.mailersend.com/v1/email]
Date: 2021-02-26 19:49
Status: 401
Content-Type: application/json
Size: 30 B
> rsp_content <- content(response, as = "parsed", type = "application/json")
> rsp_content
$message
[1] "Unauthenticated."
R Script to send an email
library("httr")
# MailerSend API Key
apiKeyMS <- Sys.getenv("MS_KEY")
# Email header info
email_from = "noreply#example.ca"
email_from_name = "Joe"
email_subject <- "Joe Update"
email_to <- "joe#gmail.com"
# Email Body
email_text <- "This is my email"
email_html <- "This is my email"
# Send Email
ms_url <- paste0("https://api.mailersend.com/v1/email")
response <- POST(ms_url,
add_headers("Authorization: Bearer" = apiKeyMS,
"X-Requested-With" = "XMLHttpRequest",
"Content-Type" = "application/json"),
body = list(
"subject" = email_subject,
"from" = email_from,
"from_name" = email_from_name,
"to" = email_to,
"text" = email_text,
"html" = email_html
), encode = "json")
#############################################################
Basic MailerSend cURL instructions
curl -X POST \
https://api.mailersend.com/v1/email \
-H 'Content-Type: application/json' \
-H 'X-Requested-With: XMLHttpRequest' \
-H 'Authorization: Bearer {place your token here without brackets}' \
-d '{
"from": {
"email": "your#email.com"
},
"to": [
{
"email": "your#email.com"
}
],
"subject": "Hello from MailerSend!",
"text": "Greetings from the team, you got this message through MailerSend.",
"html": "Greetings from the team, you got this message through MailerSend."
}'
I don't know R at all, but I would guess your bearer token is incorrect.
The header key is Authorization and the value should be "Bearer {place your token here without brackets}"
You have to have these three headers
-H 'Content-Type: application/json' \
-H 'X-Requested-With: XMLHttpRequest' \
-H 'Authorization: Bearer {place your token here without brackets}' \`
What is the correct way of writing this Curl POST in R?
I would like to have R read the contents of a file as "values" in the post form.
curl -X POST https://api.priceapi.com/jobs \
-d "token=token" \
-d "country=country" \
-d "source=source" \
-d "currentness=currentness" \
-d "completeness=completeness" \
-d "key=key" \
-d 'values=<values>'
So far I have this-
library(RCurl)
library(RJSONIO)
url = "https://api.priceapi.com/jobs"
file.name = ".../output 1 .txt"
results = postForm(url, token="token",
country="country,
source="source",
currentness="currentness",
completeness="completeness,
key="key",
values=fileUpload(filename = file.name))
It returns "Error: Bad Request"
I also tried it using httr post request-
r = POST(url, body = list(token="token",
country="country,
source="source",
currentness="currentness",
completeness="completeness,
key="key",
values=upload_file(file.name)) )
Here upload_file is not uploading the contents of the file but, I am guessing it is passing the path to the file (as a string) into the "values" parmeter.
Naturally that does not return the correct results.
The result of the httr POST request is;
Response [https://api.priceapi.com/jobs]
Date: 2016-12-13 10:11
Status: 400
Content-Type: application/json; charset=utf-8
Size: 228 B
{
"success": false,
"reason": "parameter value invalid",
"parameter": "value",
"valid values": "An array or a string containing values separated by newline",
"comment": "Make sure the parameter 'value' has a valid value!"
I could solve this by using
file=readLines(".../output 1.txt")
inputValues <- paste(file,collapse="\n")
and then passing inputValues in the values parameter.