Using google oauth2 with php mailer - oauth-2.0

When I request a token i get a GET response of
> Showing GET Array (
> [state] => 1025628ef33hdjs29342fafbd6605560
> [code] => 4/yQE9qQ4S99UeKzjwz5W0slCx34d9ff4kxfYEhESLo80XDKH04SStj3xW4b0UrUSLryaUC2o3tbPtajeYgkQR4g
> [scope] => email profile openid https://www.googleapis.com/auth/userinfo.email
> https://www.googleapis.com/auth/userinfo.profile
> [authuser] => 0
> [hd] => mywebsite.net
> [prompt] => none )
My question is what is the parameter [code]
I am using this for phpmailer and is the parameter [code] the refreshtoken?
//Create a new OAuth2 provider instance
$provider = new Google(
[
'clientId' => $clientId,
'clientSecret' => $clientSecret,
]
);
//Pass the OAuth provider instance to PHPMailer
$mail->setOAuth(
new OAuth(
[
'provider' => $provider,
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'refreshToken' => $refreshToken,
'userName' => $email,
]
)
);
As I am only getting the following response when I send mail and no mail is being recieved
2020-04-04 14:06:44 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP k18sm8991709qkh.46 - gsmtp
2020-04-04 14:06:44 CLIENT -> SERVER: EHLO simplifiedchurch.net
2020-04-04 14:06:44 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [100.8.194.132]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2020-04-04 14:06:44 CLIENT -> SERVER: STARTTLS
2020-04-04 14:06:44 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
2020-04-04 14:06:44 CLIENT -> SERVER: EHLO simplifiedchurch.net
2020-04-04 14:06:44 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [100.8.194.132]250-SIZE 35882577250-8BITMIME250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8

Part of the answer is I was getting a grant error. The grant error was caused by the requirement to enable the gmail app to run phpmailer, which I did not notice at first.

Related

How to fix getFederationToken returns 403 not authorized error after upgrading from SDK version 1 to 3

We have existing code that uses AWS PHP SDK version 1 AmazonSTS()->get_federation_token(). After upgrading to SDK version 3, the same call using the same credentials, resource and policy returns a 403 not authorized error.
Version and region appear to be the same. The policy json is the same. The user credentials used to make the call are the same (and if I switch back to the SDK v1 they still work). I have the debug option set but it doesn't appear to provide any additional information as to why the same user it not authorized to perform the same function getFederationToken on the same federated user.
Old code that works:
$client = new AmazonSTS();
$policy = new stdClass();
$policy->Statement = [
'Sid' => 'randomstatementid' . time(),
'Action' => ['s3:*'],
'Effect' => 'Allow',
'Resource' => 'aws:s3:::' . $AWS_BUCKET . '*'
];
// Fetch the session credentials.
$response = $client->get_federation_token('User1',array(
'Policy' => json_encode($policy),
'DurationSeconds' => $NUMSECS
));
New code that returns 403 error:
$client = new Aws\Sts\StsClient([
'region' => 'us-east-1',
'version' => '2011-06-15',
]);
$policy = new stdClass();
$policy->Statement = [
'Sid' => 'randomstatementid' . time(),
'Action' => ['s3:*'],
'Effect' => 'Allow',
'Resource' => 'aws:s3:::' . $AWS_BUCKET . '*'
];
try {
$response = $client->getFederationToken([
'Name' => 'User1',
'Policy' => json_encode($policy),
'DurationSeconds' => $NUMSECS,
]);
} catch (Exception $e) {
var_dump($e);
die();
}
The first example returns temporary credentials for the federated user User1.
The second example returns 403 forbidden error (I'm hiding the actual account id):
<Error>
<Type>Sender</Type>
<Code>AccessDenied</Code>
<Message>User: arn:aws:iam::[account id]:user/portal is not authorized to perform: sts:GetFederationToken on resource: arn:aws:sts::[account id]:federated-user/User1</Message>
</Error>
Turns out I was looking at the wrong credentials. I found the correct credentials hard-coded in the script :(

Invoke Rest API using Oauth 2.0 token in logstash http output plugin

I am trying to publish log events to my rest API using logstash http output plugin. It works if there is no authorization or I enable the basic authentication But my requirement is to invoke the API using Oauth 2.0 access tokens. When I specify the Authorization header with access token I am getting 401 error. From SOAPUI I have tested token is working fine. Below are the logstash configs.
output {
if [type] == "error" {
if "loglevelerror" in [tags] {
#*******************************************************************
# Sending Messages to EventAPI
#*******************************************************************
http {
url => "http://serverip:8281/events"
headers => {
"Authorization" => "Bearer c505e8f7-ecb3-346f-8216-f906965edc17"
"RequestSource" => "agent"
"Accept" => "application/json"
}
connect_timeout => 60
socket_timeout => 60
http_method => "post"
format => "json"
mapping => [my mappings]
}
}
}
}
Any help would be a great favour.

authentication using google spreadsheet api

https://developers.google.com/gdata/articles/using_ruby
I'm following the "Authentication | Using the Google Spreadsheets API" section in above tutorial.
rb(main):008:0> require 'net/https'
=> true
irb(main):009:0> http = Net::HTTP.new('www.google.com', 443)
=> #<Net::HTTP www.google.com:443 open=false>
irb(main):010:0> http.use_ssl = true
=> true
irb(main):011:0> path = '/accounts/ClientLogin'
=> "/accounts/ClientLogin"
# Now we are passing in our actual authentication data.
# Please visit OAuth For Installed Apps for more information
# about the accountType parameter
irb(main):014:0> data = \
irb(main):015:0* 'accountType=HOSTED_OR_GOOGLE&Email=your email' \
irb(main):016:0* '&Passwd=your password' \
irb(main):017:0* '&service=wise'
irb(main):018:0> headers = \
irb(main):019:0* { 'Content-Type' => 'application/x-www-form-urlencoded'}
=> {"Content-Type"=>"
application/x-www-form-urlencoded"}
# Post the request and print out the response to retrieve our authentication token
irb(main):020:0> resp, data = http.post(path, data, headers)
=> #<Net::HTTPLengthRequired 411 Length Required readbody=true>
I'm supposed to get "=> [#, "SID=DQAAAIIAAADgV7j4F-QVQjnxdDRjpslHKC3M ... [ snipping out the rest of the authentication strings ]" after the POST. I put my gmail id and password in email and password.
What is problem?
It's possible that they removed the service today. When I request this page https://www.google.com/accounts/ClientLogin I receive 404 (not found).

Google_AuthException [ 400 ]: Error fetching OAuth2 access token, message: 'invalid_grant'

The problem arises when I get the code and makes a request for a token. For authorization using code that works fine on other projects. I check Credentials in developer console and my config file. Attempts to connect the authorization from other sites and other accounts yielded nothing. I checked redirects, headers, but found nothing.
$request = Google_Client::$io->makeRequest(new Google_HttpRequest('https://accounts.google.com/o/oauth2/token', 'POST', array(), array(
'code' => $_GET['code'],
'grant_type' => 'authorization_code',
'redirect_uri' => $this->redirectUri,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret
)));
This request return "Error fetching OAuth2 access token, message: 'invalid_grant'"

Failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request - OAuth 2.0 POST

I am working with YouTube APIs for my college project, and I keep getting an error. Here I send them to the authorisation page to log in, when they allow access it sends the $_GET['code'] string back. Then I send this along with some other data and it should send back a JSON object. Instead I am just getting
Warning: file_get_contents(https://accounts.google.com/o/oauth2/token)
[function.file-get-contents]: failed to open stream: HTTP request
failed! HTTP/1.0 400 Bad Request in http://www.example.net/callback.php on line 27
I have replaced my domain with example.net just for security
urlencode($_GET['code']),
'client_id' => urlencode('111522767640.apps.googleusercontent.com '),
'client_secret' => urlencode('secret'),
'redirect_uri' => urlencode('http://example.net/callback.php'),
'grant_type' => urlencode('authorization_code')
)
);
$params =
array('http' =>
array(
'method' => 'POST /o/oauth2/token HTTP/1.1',
'header' => 'Host: accounts.google.com\r\n'.
'Content-Type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($params);
$result = file_get_contents('https://accounts.google.com/o/oauth2/token', false,$context);
var_dump($_SESSION);
var_dump($result);
}
else //If code isnt set, user must have come here erroniously or has denied access to this program
{
//header( 'Location: www.example.net/error.php' ) ;
}
?>
file_get_contents is going to make a GET request to the url specified, but oauth2/token needs a POST request.
See reference Google OAuth2, PHP HTTP.
if you are using oauth2, goto libraries/oauth2/provider.php and uncomment the code line 182 shows
$ci = get_instance();
$ci->load->spark('curl/1.2.1');
$ci->curl
->create($url)
->post($params, array('failonerror' => false));
$response = $ci->curl->execute();
Here's how to do the Google oAuth properly:
$config = (object) array(
'CLIENT_ID' => 'AAAAA',
'CLIENT_SECRET' => 'BBBBB',
'REFRESH_TOKEN' => 'CCCCC',
);
$sJSON = file_get_contents('https://www.googleapis.com/oauth2/v4/token',FALSE,
stream_context_create(array('http'=>array(
'ignore_errors' => TRUE, // see errors in response instead of empty on error
'method' => 'POST',
'header' => array(
'Content-Type: application/x-www-form-urlencoded'
),
'content' => http_build_query(array(
'grant_type' => 'refresh_token',
'client_id' => $config->CLIENT_ID,
'client_secret' => $config->CLIENT_SECRET,
'refresh_token' => $config->REFRESH_TOKEN
))
)))
);
You can then use json_decode() to parse $sJSON into an object and then retrieve the access_token property.
For those who are wondering how to get the CLIENT_ID, CLIENT_SECRET, and REFRESH_TOKEN, watch this video. It's not easy. In my case, I needed to do this for Google Adwords API. So, I had to get my Developer Token and Login Customer ID from https://ads.google.com/home/tools/manager-accounts. Then, I had to go to https://console.developers.google.com/apis/credentials with this guide to generate a Client ID and Client Secret. Then, I followed this guide to learn how to get my Refresh Token.

Resources