How to get a Google API token - token

I need to get the Google validation token to use with Google APIs, but my code does not work.
$client_id = '495225261106.apps.googleusercontent.com';
$client_secret = urlencode('MY_SECRET_CDE');
$redirect_uri = urlencode('http://MYPAGE.net/test.php');
//$grant_type = urlencode('authorization_code'); //it does not work either.
$grant_type = 'authorization_code';
$post_string = "code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp6&client_id={$client_id}&client_secret={$client_secret}&redirect_uri={$redirect_uri}&grant_type={$grant_type}";
//echo_key_value('post_string',$post_string);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch); // Execute the HTTP command
$errmsg = curl_error($ch);
if($errmsg) echo $errmsg;
The output is:
{"error":"invalid_grant"}

You may find it easier to use Google APIs, especially OAuth stuff, via one of the official client libraries.
Here's a link to the PHP one: http://code.google.com/p/google-api-php-client/
And a link to the docs on OAuth 2.0 with the library (with some great example code): http://code.google.com/p/google-api-php-client/wiki/OAuth2

Don't you have to put " curl_setopt($ch, CURLOPT_POST, true); " before using postfields? Mine is working and except that and I didn't used urlencode on my secret, it's the same

Setup Instructions
Go to the Google Developers Console
https://console.developers.google.com/project Select your project or
create a new one (and then select it)
Enable the API for your
project In the sidebar on the left, expand APIs & auth > APIs Search
for "drive" Click on "Drive API" click the blue "Enable API" button
Create a service account for your project In the sidebar on the left,
expand APIs & auth > Credentials Click blue "Add credentials" button
Select the "Service account" option
Select "Furnish a new private
key" checkbox Select the "JSON" key type option
Click blue "Create"
button your JSON key file is generated and downloaded to your machine
(it is the only copy!)
open the json file and save your private key to a file called rsa
note your service account's email address
(also available in the JSON key file) Share the doc (or docs) with
your service account using the email noted above
based on information from ( a fantastic doc )
https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
for a list of possible API scopes set
https://developers.google.com/identity/protocols/googlescopes#sheetsv4
for a purely bash based solution
#!/bin/bash
client_email='your client email'
scope='https://www.googleapis.com/auth/spreadsheets.readonly'
jwt1=`echo -n '{"alg":"RS256","typ":"JWT"}' | openssl base64 -e`
exp=$(($(date +%s)+3600))
iat=$(date +%s)
jwt2=`echo -n '{\
"iss":"'"$client_email"'",\
"scope":"'"$scope"'",\
"aud":"https://accounts.google.com/o/oauth2/token",\
"exp":'$exp',\
"iat":'$iat'}' | openssl base64 -e`
jwt3=`echo -n "$jwt1.$jwt2" | tr -d '\n' | tr -d '=' | tr '/+' '_-'`
jwt4=`echo -n "$jwt3" | openssl sha -sha256 -sign rsa | openssl base64 -e`
jwt5=`echo -n "$jwt4" | tr -d '\n' | tr -d '=' | tr '/+' '_-'`
echo $jwt3
echo $jwt5
curl -H -vvv "Content-type: application/x-www-form-urlencoded" -X POST "https://accounts.google.com/o/oauth2/token" -d \
"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=$jwt3.$jwt5"
for a javascript nodejs based solution see
https://gist.github.com/cloverbox/5ce51a1d8889da9045c5b128a3a2502f

Related

How to get the sasKey or connectionString when developing a module?

I am attempting to write a module where I cannot use the current ModuleClient.CreateFromEnvironmentAsync() and would like to get the module connection string (or SASKey) so I can generate a SAS token and authenticate.
I know that at one time (and in the IoTEdgeDev container) the environment variable EdgeHubConnectionString existed and was later removed. How can I derive the sasKey in code in a module? Imaging if I needed/wanted to use Paho in the module instead of the MSFT provided SDK.
Update
So I guess I have to sign the URI to create a connection string, similar to manually creating a connection string.
I have tried the code below, but the signature does not match what I get with Azure IoT Explorer. Any help would be appreciated. Reference: https://github.com/Azure/iotedge/blob/d2c331d605a846911019364a31a7d098e1e2fc45/edgelet/workload/docs/WorkloadApi.md
# expecting curl, base64 and jq to be installed
epoch=$(printf '%(%s)T\n' -1)
epoch=$(($epoch+86400))
dataToSign=$IOTEDGE_IOTHUBHOSTNAME"%2Fdevices%2F"$IOTEDGE_DEVICEID"%2Fmodules%2F"$IOTEDGE_MODULEID
signedData=$(echo -n $dataToSign'\n'$epoch | base64 -w 0)
signature=$(curl --unix-socket /var/run/iotedge/workload.sock http://127.0.0.1/modules/$IOTEDGE_MODULEID/genid/$IOTEDGE_MODULEGENERATIONID/sign?api-version=$IOTEDGE_APIVERSION \
--header "Content-Type: application/json" --request POST --data '{"data": "'$signedData'", "keyId": "", "algo": "HMAC-SHA256"}' \
| jq -r ".digest")
SASToken="SharedAccessSignature=SharedAccessSignature sr=$dataToSign&sig=$signature&se=$epoch"
ConnectionString="HostName=$IOTEDGE_IOTHUBHOSTNAME;DeviceId=$IOTEDGE_DEVICEID;ModuleId=$IOTEDGE_MODULEID;$SASToken"
I took a look at the implementation of ModuleClient.CreateFromEnvironmentAsync() in the C# SDK. It uses the following environment variables to create the connection string:
- IOTEDGE_WORKLOADURI URI for iotedged's workload API
- IOTEDGE_DEVICEID Device identifier
- IOTEDGE_MODULEID Module identifier
- IOTEDGE_MODULEGENERATIONID Module generation identifier
- IOTEDGE_IOTHUBHOSTNAME IoT Hub host name
- IOTEDGE_AUTHSCHEME Authentication scheme to use; must be "sasToken"
It seems the SAS token is created in the ModuleAuthenticationWithHsm class, you might be able to base your code on this?
So after hours of iteration, here is how to call the sign API to get a SAS Token:
# expecting curl, base64 and jq to be installed in the Linux OS
epoch=$(printf '%(%s)T\n' -1)
epoch=$(($epoch+86400))
WORKLOADURI=$(echo $IOTEDGE_WORKLOADURI | sed "s|unix://|""|g")
uri=$(echo $IOTEDGE_IOTHUBHOSTNAME"/devices/"$IOTEDGE_DEVICEID"/modules/"$IOTEDGE_MODULEID | sed "s|/|%2F|g")
signedData=$(echo -n $uri$'\n'$epoch | base64 -w 0)
signature=$(curl --unix-socket $WORKLOADURI http://127.0.0.1/modules/$IOTEDGE_MODULEID/genid/$IOTEDGE_MODULEGENERATIONID/sign?api-version=$IOTEDGE_APIVERSION \
--request POST --data '{"data": "'$signedData'", "keyId": "", "algo": "HMAC-SHA256"}' \
| jq -r ".digest" | sed "s|=|%3D|g" | sed "s|+|%2B|g" | sed "s|/|%2F|g")
# here is our SAS Token
SASToken="SharedAccessSignature=SharedAccessSignature sr=$uri&sig=$signature&se=$epoch"
# here is a connection string with the SAS Token
ConnectionString="HostName=$IOTEDGE_IOTHUBHOSTNAME;DeviceId=$IOTEDGE_DEVICEID;ModuleId=$IOTEDGE_MODULEID;$SASToken"

How to get the API token for Jenkins

I am trying to use the Jenkins REST API. In the instructions it says I need to have the API key. I have looked all over the configuration pages to find it. How do I get the API key for Jenkins?
Since Jenkins 2.129 the API token configuration has changed:
You can now have multiple tokens and name them. They can be revoked individually.
Log in to Jenkins.
Click you name (upper-right corner).
Click Configure (left-side menu).
Use "Add new Token" button to generate a new one then name it.
You must copy the token when you generate it as you cannot view the token afterwards.
Revoke old tokens when no longer needed.
Before Jenkins 2.129: Show the API token as follows:
Log in to Jenkins.
Click your name (upper-right corner).
Click Configure (left-side menu).
Click Show API Token.
The API token is revealed.
You can change the token by clicking the Change API Token button.
The non UI way to do this post Jenkins 2.129 is:
curl 'https://<jenkinsURL>/me/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken' \
--data 'newTokenName=foo' \
--user username:Password
which returns:
{
"status": "ok",
"data": {
"tokenName": "foo",
"tokenUuid": "<uuid>",
"tokenValue": "<redacted>"
}
}
Pre Jenkins 2.129
curl http://<username>:<password>#<jenkins-url>/me/configure
Tested in Jenkins 2.225
After making research for several hours I could find the answer:
The API token is used instead of the CSFR token. However, what happens if you want to make authentication from any other client (Postman, CLI, cURL, etc.)?
First you need to get a CSFR token and save the information in a cookie with --cookie-jar
Request
curl -s --cookie-jar /tmp/cookies -u username:password
http://localhost:8080/crumbIssuer/api/json
Response
{
"_class": "hudson.security.csrf.DefaultCrumbIssuer",
"crumb": "bc92944100d12780cfc251c9255f3f323a475562b4ee0d8b9cc6e4121f50a450",
"crumbRequestField": "Jenkins-Crumb" }
Then we can read the cookie with --cookie and generate the new token:
Request
curl -X POST -H
'Jenkins-Crumb:your_crumb_token_generated_above'
--cookie /tmp/cookies http://localhost:8080/me/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken?newTokenName=\your_token_name
-u username:password
Response
{
"status": "ok",
"data": {
"tokenName": "my android token",
"tokenUuid": "c510e26c-b2e8-4021-bf79-81d1e4c112af",
"tokenValue": "11a2a0c91913d1391d8e8cb155ca714581"
} }
How to a generate Jenkins API token
The following commands need curl and jq. Execute them in the same session.
# Change the following appropriately
JENKINS_URL="http://localhost:8080"
JENKINS_USER=admin
JENKINS_USER_PASS=admin
Get the Crumb
JENKINS_CRUMB=$(curl -u "$JENKINS_USER:$JENKINS_USER_PASS" -s --cookie-jar /tmp/cookies $JENKINS_URL'/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)')
Get the access token
ACCESS_TOKEN=$(curl -u "$JENKINS_USER:$JENKINS_USER_PASS" -H $JENKINS_CRUMB -s \
--cookie /tmp/cookies $JENKINS_URL'/me/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken' \
--data 'newTokenName=GlobalToken' | jq -r '.data.tokenValue')
Consecutive API calls
Instead of the password, you need to use the token with the username along with the crumb that was generated.
curl -u $JENKINS_USER:$ACCESS_TOKEN \
-H $JENKINS_CRUMB \ ..........

PHP Curl but the HTML is Encrypted and SSL Certificate: unable to get local issuer certificate

I want to parse the HTML from this site, I already try to use :
file_get_contents
Simple HTML DOM
but the result is awful like this :
then I try PHP CURL by using php html parser, I found the error is SSL certificate problem: unable to get local issuer certificate
After searching the answer, then I read using curl to access https, and I try to get the certificate by using the step in that article but the result is same
the question is, why the parsing result is like that? now, I don't know what to do :(
The page is compressed with gzip.
curl -k --compressed https://inaproc.lkpp.go.id/v3/daftar_lpse
For PHP
$ch = curl_init("https://inaproc.lkpp.go.id/v3/daftar_lpse");
curl_setopt($ch, CURLOPT_ENCODING , "");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
echo $output;

Erlang hackney : send a mail in mailgun.com using attachement

I'm trying to send an email via mailgun.com using the hackney and I have some issues sending attachments (which requires multipart).
https://documentation.mailgun.com/api-sending.html#sending
Basically my interest fields are:
from
to
subject
text
attachment File attachment. You can post multiple attachment values. Important: You must use multipart/form-data encoding when sending attachments.
I tried the following:
PayloadBase =[
{<<"from">>, From},
{<<"to">>, To},
{<<"subject">>, Subject},
{<<"text">>, TextBody},
{<<"html">>, HtmlBody}
],
Payload = case Attachment of
null ->
{form, PayloadBase};
_->
{multipart, PayloadBase ++ [{file, Attachment}]}
end,
But for some reason the attachment is not sent.. Everything else works as expected.
I don't see how I can set the filed name to "attachment" as required by mailgun .. at this this is what I suspect beeing wrong
I haven't used mailgun but I believe that you would need to put attachment as the field name. See examples at the bottom of the page you posted:
curl -s --user 'api:YOUR_API_KEY' \
https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages \
-F from='Excited User <YOU#YOUR_DOMAIN_NAME>' \
-F to='foo#example.com' \
-F cc='bar#example.com' \
-F bcc='baz#example.com' \
-F subject='Hello' \
-F text='Testing some Mailgun awesomness!' \
--form-string html='<html>HTML version of the body</html>' \
-F attachment=#files/cartman.jpg \
-F attachment=#files/cartman.png
It will be easier if you make it working with curl first, then you can debug what headers curl sends to the server. And then you can mimic that in Erlang.
This post explains what multipart/form-data is and points to the W3 document that provides examples how the data should be encoded.
The following code will fix the problem:
Payload2 = case Attachment of
null ->
{form, PayloadBase};
_->
FName = hackney_bstr:to_binary(filename:basename(Attachment)),
MyName = <<"attachment">>,
Disposition = {<<"form-data">>, [{<<"name">>, <<"\"", MyName/binary, "\"">>}, {<<"filename">>, <<"\"", FName/binary, "\"">>}]},
ExtraHeaders = [],
{multipart, PayloadBase ++ [{file, Attachment, Disposition, ExtraHeaders}]}
end,
Silviu

Using curl for lira API with a period in the fixVersion jql

I've tried various iterations of using either ", ' and ` to enclose a curl query to an instance of jira in order to get all issues for a particular fix Version.
curl -D- -u username:password -X POST -H "Content-Type: application/json" -d '{"jql":"project = PROJ AND fixVersion=Version-1.2.3"}' "https://thejirainstall.com/jira/rest/api/2/search"
However, using this and a couple of other change on fixVersion such as:
fixVersion="Version-1.2.3"
or
fixVersion=\"Version-1.2.3\"
or
fixVersion=Version-1\u002e2\u002e3
Add and remove quotes at will.
The ones that don't fail outright return:
{"errorMessages":["Error in the JQL Query: '\\.' is an illegal JQL escape sequence. The valid escape sequences are \\', \\\", \\t, \\n, \\r, \\\\, '\\ ' and \\uXXXX. (line 1, character 38)"],"errors":{}}
How do I either escape periods . or add another set of quotes?
Ok, so it turns out that Jira doesn't permit version names in jql syntax. The version id must be used instead.
And, in order to get the version id you must parse the result from https://thejirainstall.com/jira/rest/api/2/project/ON/versions?
This now means that I have to use a JSON parser anyway. So, now I'm using jq via homebrew install jq
My current solution is to write a bash script as below:
JIRA_FIXVERSION
fixVersionQuery='https://thejirainstall.com/jira/rest/api/2/project/ON/versions?';
myJSONResponse=`curl -u username:password -X GET -H "Content-Type: application/json" --insecure --silent $fixVersionQuery |jq '.[] | {id,name} | select(.name=="Version-1.2.3" | .["id"]'`;
echo $myJSONResponse;

Resources