when i am trying to create an event using google api i have an error: 1631 connection failed.
trying to access using "Insert from URL"
where $responseAPI is a variable to store the response
URL:
"https://www.googleapis.com/calendar/v3/calendars/" & $calendarId & "/events? access_token" & $accessToken
cURL:
"-x POST -H \"Content-type: application/json\" --data & Quote($data)
Related
I'm learning how to fetch data using an API in R. I understand that the aim of httr is to provide a wrapper for the curl package.
The documentation I'm following so that I make requests to the API has the following HTTP request format. This code below will be used to generate a token
curl -s \
-d "client_id=clientid” \
-d "username=user” \
-d "password=pwd” \
-d "grant_type=password" \
-d "scope=openid email" \
"https://auth.com/token"
Afterward, I'll use the token to now communicate with the API using this request
curl --header "Content-Type: application/json" \
--header "Accept: application/+json" \
--header "Authorization: Bearer token_goes_here“ \
--request GET \
--url "https://api-sitename.org/sections?parent_id=0"
Initially, I run these two requests in a terminal and they were successful, I got a response in JSON format. My question is, how do I run these requests in an R script such that I get a responses and they're it's stored in R studio global environment? My goal is to finally load the dataset from the API to the Rstudio working environment.
T
Here is something to get you started:
library(httr)
resp <- POST("https://auth.com/token",
body=list(client_id="clientid",
username="user",
password="pwd",
grant_type="password",
scope="openid email")
)
#parse for auth token here
content(resp, "text")
get_resp <- GET("https://api-sitename.org/sections?parent_id=0",
add_headers("Content-Type"="application/json",
Accept="application/+json",
"Authorization"=paste("Bearer", token))
I was able to successfully get my API call in R by replacing the content in header to body.
Here is my code
#' Th base url
base_url <- "your/url/endpoint/for/token"
# base64 encoded client id, my end-point requires to encone the client id to base64
c_id <- RCurl::base64(txt = "clinetid:sceret", mode = "character")
#' headers
headers <- httr::add_headers(
"Authorization" = paste("Basic",c_id, sep = " ")
)
# move everything else to the body. grant_type and password were requested by the endpoint
body <- list(
username = "your username",
password = "your password",
grant_type = "password",
scope = "read"
)
#' post call to get the token
httr::POST(
url = base_url,
body = body,
config = headers,
httr::accept_json()
)
When I had the user name and password in the body, I received 400 and 403 errors. Once I moved them o the body received 200 status and the token was successfully retrieved. If you can provide what you tried in R, can help you troubleshoot.
From the development in Windev I use Oauth 2.0 for authorization to get access to the outlook mail from a user.
The application is registered at https://apps.dev.microsoft.com without the Implicit workflow.
After the user enters the credentials, an Authorization Code is returned.
With the new code the Bearer Token is requested with a HTTP Post command.
So far, so good.
Only that the response gives an error message that makes no sense to me.
In code:
m_sHTTPUrl = "client_id=" + m_sClientID + "&client_secret=" ...
+ m_sClientSecret ...
+ "&redirect_uri=" + m_sRedirectURL + "&code=" + m_sAuthToken ...
+ "&grant_type=authorization_code"
m_sHTTPres = ""
LogLocalFile("GetAccessToken - " + m_sTokenURL + " // " + m_sHTTPUrl)
cMyRequest is httpRequest
cMyRequest..Method = httpPost
cMyRequest..URL = m_sTokenURL
cMyRequest..ContentType = "application/x-www-form-urlencoded"
cMyRequest..Header["grant_type"] = "authorization_code"
cMyRequest..Header["code"] = m_sAuthToken
cMyRequest..Header["client_id"] = m_sClientID
cMyRequest..Header["client_secret"] = m_sClientSecret
cMyRequest..Header["scope"] = m_sScope
cMyRequest..Header["redirect_uri"] = m_sRedirectURL
//cMyRequest..Content = m_sHTTPUrl
cMyResponse is httpResponse = HTTPSend(cMyRequest)
m_sHTTPres = cMyResponse.Content
In a logfile I requested the used parameters and the content of the httpResponse:
GetAccessToken - https://login.microsoftonline.com/common/oauth2/v2.0/token // grant_type=authorization_code
&code=xxxxxxx
&scope=openid+offline_access+User.Read+Email+Mail.Read+Contacts.Read
&redirect_uri=http://localhost/
&client_id=xxxxxxx
&client_secret=xxxxxxx
GetAccessToken - error = invalid_request
GetAccessToken - error_description = AADSTS90014: The request body must contain the following parameter: 'grant_type'.
The grant_type is in the header as it is supposed to be.
Does anybody have any clue of what is needed to get the OAUTH2 working ?
You shouldn't send grant_type neither in params nor in headers. Those should be sent in body params then only it will work.
Url: https://login.microsoftonline.com/common/oauth2/v2.0/token
client_id, scope and redirect_uri params can be sent as query params.
where as grant_type, code and client_secret should sent in body params.
grant_type:authorization_code,
code: {code you got from the authorization step},
client_secret: ****
You need to pass everything in body as form-data:
curl --location --request POST 'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token' \
--form 'grant_type=authorization_code' \
--form '<the code you have got from the authorization endpoint' \
--form 'client_secret=****' \
--form 'client_id=********' \
--form 'scope=m_sScope' \
--form 'redirect_uri=http://localhost/'
you should change the content type as : application/x-www-form-urlencoded
the body must to be formated as bellow:
client_id=8cfbe8ac-8775-4c56-9302-k9d5a42cbf98
&client_secret=BOy7Q~pGvXF.SWshX72mmMnQeAkvN5elHWiYT
&grant_type=client_credentials
&resource=https://miurl.com
I finally got this right after referring to multiple answers.
POST https://login.microsoftonline.com//oauth2/token
--make sure to enter the ID directly without <,>
Use 'x-www-form-urlencoded' format for the Body.
Enter Keys & Values for the below parameters
client_id - Client_ID on your Azure App
client_secret - client_secret value and not the key. Note that this value is available only for the first time upon the client secret key creation
grant_type - client_credentials (static words, don't try to look for the value)
resource - App ID URI
reference link - https://learn.microsoft.com/en-us/previous-versions/azure/dn645543(v=azure.100)?redirectedfrom=MSDN
when providing "Default Scope" value must be full name example , "User.Read" correct value can get from azure AD APP -> Api Permission
curlHandle <- getCurlHandle(ssl.verifypeer = FALSE)
url = "http://www.google.com"
Responseresult=postForm(url,curl=curlHandle,style="POST")
This is the code that I have used and I want to get the status code and the success or failure message that is sent by the server but by only using curl.
I try to build below:
by following: this steps
however, i keep receiving redirect uri missmatch when i tried to exchange auth code (given by my mobile app) to google server - which i couldn't understand because technically there is no redirect uri required for my flow case...
here are the details:
in Android Client:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(new Scope(Scopes.DRIVE_APPFOLDER))
.requestServerAuthCode(serverClientId, false)
.build();
/**** bla.... ****/
GoogleSignInAccount acct = result.getSignInAccount();
String authCode = acct.getServerAuthCode();
/**** android app will send this authCode to my server ****/
/**** sample authCode: 4/Jny2Mxxx3x09sy4pqY3ZAwSTEz8rw2xxxxC-4VxxxxM
in my backend server:
try:
# i receive authCode correctly from android app.
# and use authCode to exchange to Access Token to google server as below:
credentials = client.credentials_from_clientsecrets_and_code(
app.config.get('GG_APP_SECRET'),
['https://www.googleapis.com/auth/plus.me', 'profile', 'email'],
authCode)
except Exception as e:
log.info('>>>>> I always receive: redirect uri missmatch here: %s <<<<<', e)
return generate_response(code=400, error=False, type='Fail', message=str(e))
this is curl from my backend server:
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \
"authCode": "4/HP_cP_t70pgBrxxx7sjzCil7kaUHkxxxerdkMxxxrRg" \
}' 'http://localhost:5005/api/user/register/gg'
this is my console settings:
Questions:
is the serverClientId in android client suppose to be the clientID of above image?
what is the redirect uri that i should put in google console above?
what should i set/configure for my redirect uri? or is there any specific settings that i need to do?
Ok I go it,
if you see this
you will found out:
def credentials_from_clientsecrets_and_code(filename, scope, code,
message=None,
redirect_uri='postmessage',
http=None,
cache=None,
device_uri=None):
and you realize that redirect_uri = 'postmessage' which in my case i dont have post message.
so what i do is to match that redirect_uri with authorize redirect uri that i have in google console
so for my case in my question above, i change my python code to:
credentials = client.credentials_from_clientsecrets_and_code(
app.config.get('GG_APP_SECRET'),
['https://www.googleapis.com/auth/plus.me', 'profile', 'email'],
authCode, redirect_uri='https://developers.google.com/oauthplayground')
I get a 400 Bad Request with this code:
Dim client As New WebClient()
client.Headers.Add("content-type", "application/x-www-form-urlencoded")
client.Headers.Add("Authorization", "Bearer **my-access-token-here**")
Dim groupsResponse As String = client.UploadString("https://graph.windows.net/myorganization/groups", "api-version=1.6")
I get a 401 Unauthorized with this code:
Dim client As New WebClient()
client.Headers.Add("content-type", "application/x-www-form-urlencoded")
client.Headers.Add("Authorization", "Bearer **my-access-token-here**")
Dim groupsResponse As String = client.DownloadString("https://graph.windows.net/myorganization/groups?api-version=1.6")
I'm getting my accesstoken from this OAuth2 endpoint:
https://login.microsoftonline.com/**my-tentant-id-here**/oauth2/token
Where it says "myorganization" I also tried it with my tenant id in place of "myorganization". With the same results.
What am I doing wrong?
The 400 error is because you were trying to post the incorrect data format(string) to the wrong REST API endpoint.
If you want to request the groups, you can refer the REST below(refer here):
get: https://graph.windows.net/{tenant_id}/groups?api-version=1.6
For the 401 error, you may show the detail error message so that we can identity the root reason. And you can also parse the token from here to verify whether the aud claim is https://graph.windows.net and is there enough permission to call the Group REST like Group.Read.All, Group.ReadWrite.All, Directory.Read.All and Directory.ReadWrite.All.