Getting "invalid_client" when using obtained oauth token (Microsoft) with phpmailer - outlook

Can't seem to get this working. Any idea why?
This is my MS configuration:
authentication
api/permissions
token configuration (empty)
"expose an api" (empty)
Code obtaining token (works fine):
new \Stevenmaguire\OAuth2\Client\Provider\Microsoft([
'clientId' => "my_id...",
'clientSecret' => "my_secret...",
'redirectUri' => "https://example.com/get/get_oauth_token.php",
'accessType' => 'offline',
// Optional (what is this doing??)
'urlAuthorize' => 'https://login.windows.net/common/oauth2/authorize',
'urlAccessToken' => 'https://login.windows.net/common/oauth2/token',
'urlResourceOwnerDetails' => 'https://outlook.office.com/api/v1.0/me'
]);
$authUrl = $provider->getAuthorizationUrl([
'scope' => ['wl.basic', 'wl.signin', 'wl.emails'] // no idea what I need here and what not - does it have to align with the app permissions?
]);
$_SESSION['oauth2state'] = $provider->getState();
header('Location: ' . $authUrl);
Using token to send mail:
$mail = new PHPMailer();
$mail->isSMTP();
$mail->Timeout = 10;
$mail->Host = "smtp.office365.com"; // smtp.office365.com, outlook.office.com, smtp-mail.outlook.com which one is it even?? Doesnt make a difference
$mail->Port = 587;
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->AuthType = 'XOAUTH2';
// (omitting all mail content stuff here)
$provider = new \Stevenmaguire\OAuth2\Client\Provider\Microsoft([
'clientId' => "my_id...",
'clientSecret' => "my_secret...",
'redirectUri' => "https://example.com/get/get_oauth_token.php" // is this necessary here?
]);
//Pass the OAuth provider instance to PHPMailer
$mail->setOAuth(
new OAuth([
'provider' => $provider,
'clientId' => "my_id...",
'clientSecret' => "my_secret...",
'refreshToken' => "my_refreshToken...",
// 'oauthToken' => $token, // ? are we completely ignoring the actual access token in all of this? do we ever need to update our refresh token?
'userName' => 'me#mycompany.onmicrosoft.com' // supposed to be user that gave consent?
])
);
$mail->send();
$mail->SmtpClose();
Getting this error:
2022-09-22 17:49:08 SERVER -> CLIENT: 220 FR0P281CA0070.outlook.office365.com Microsoft ESMTP MAIL Service ready at Thu, 22 Sep 2022 17:49:07 +0000
2022-09-22 17:49:08 CLIENT -> SERVER: EHLO example.com
2022-09-22 17:49:08 SERVER -> CLIENT: 250-FR0P281CA0070.outlook.office365.com Hello [85.13.129.169]250-SIZE 157286400250-PIPELINING250-DSN250-ENHANCEDSTATUSCODES250-STARTTLS250-8BITMIME250-BINARYMIME250-CHUNKING250 SMTPUTF8
2022-09-22 17:49:08 CLIENT -> SERVER: STARTTLS
2022-09-22 17:49:08 SERVER -> CLIENT: 220 2.0.0 SMTP server ready
2022-09-22 17:49:08 CLIENT -> SERVER: EHLO example.com
2022-09-22 17:49:08 SERVER -> CLIENT: 250-FR0P281CA0070.outlook.office365.com Hello [85.13.129.169]250-SIZE 157286400250-PIPELINING250-DSN250-ENHANCEDSTATUSCODES250-AUTH LOGIN XOAUTH2250-8BITMIME250-BINARYMIME250-CHUNKING250 SMTPUTF8
Bad Request
/www/htdocs/w014af32/me/vendor/stevenmaguire/oauth2-microsoft/src/Provider/Microsoft.php(79)
#0 /www/htdocs/w014af32/me/vendor/league/oauth2-client/src/Provider/AbstractProvider.php(628): Stevenmaguire\OAuth2\Client\Provider\Microsoft->checkResponse(Object(GuzzleHttp\Psr7\Response), Array)
#1 /www/htdocs/w014af32/me/vendor/league/oauth2-client/src/Provider/AbstractProvider.php(537): League\OAuth2\Client\Provider\AbstractProvider->getParsedResponse(Object(GuzzleHttp\Psr7\Request))
#2 /www/htdocs/w014af32/me/vendor/phpmailer/phpmailer/src/OAuth.php(115): League\OAuth2\Client\Provider\AbstractProvider->getAccessToken(Object(League\OAuth2\Client\Grant\RefreshToken), Array)
#3 /www/htdocs/w014af32/me/vendor/phpmailer/phpmailer/src/OAuth.php(128): PHPMailer\PHPMailer\OAuth->getToken()
#4 /www/htdocs/w014af32/me/vendor/phpmailer/phpmailer/src/SMTP.php(598): PHPMailer\PHPMailer\OAuth->getOauth64()
#5 /www/htdocs/w014af32/me/vendor/phpmailer/phpmailer/src/PHPMailer.php(2190): PHPMailer\PHPMailer\SMTP->authenticate('', '', 'XOAUTH2', Object(PHPMailer\PHPMailer\OAuth))
#6 /www/htdocs/w014af32/me/vendor/phpmailer/phpmailer/src/PHPMailer.php(2003): PHPMailer\PHPMailer\PHPMailer->smtpConnect(Array)
#7 /www/htdocs/w014af32/me/vendor/phpmailer/phpmailer/src/PHPMailer.php(1662): PHPMailer\PHPMailer\PHPMailer->smtpSend('Date: Thu, 22 S...', 'test content\r\n')
#8 /www/htdocs/w014af32/me/vendor/phpmailer/phpmailer/src/PHPMailer.php(1500): PHPMailer\PHPMailer\PHPMailer->postSend()
#9 /www/htdocs/w014af32/me/includes/helpers/mail.php(182): PHPMailer\PHPMailer\PHPMailer->send()
#10 /www/htdocs/w014af32/me/includes/helpers/mail.php(113): mailSendSingle(Object(PHPMailer\PHPMailer\PHPMailer), Array, true)
#11 /www/htdocs/w014af32/me/get/test4.php(25): mailSend(Array)
#12 {main}
# Args:
checkResponse: [{},{"error":"invalid_client","error_description":"The client does not exist or is not enabled for consumers. If you are the application developer, configure a new application through the App Registrations in the Azure Portal at https:\/\/go.microsoft.com\/fwlink\/?linkid=2083908.","correlation_id":"4dc377bd-0d5d-4444-bdd4-82b862f86177"}]
getParsedResponse: [{}]
getAccessToken: [{},{"refresh_token":"my refreshToken..."}]
authenticate: ["","","XOAUTH2",{}]
smtpConnect: [{"ssl":{"verify_peer":false,"verify_peer_name":false,"allow_self_signed":true}}]
smtpSend: ["Date: Thu, 22 Sep 2022 19:49:08 +0200\r\nTo: John Doe <me#example.com>\r\nFrom: John Doe <me#mycompany.onmicrosoft.com>\r\nReply-To: John Doe <me#mycompany.onmicrosoft.com>\r\nSubject: test mail\r\nMessage-ID: <AAtH5DrcPQ9Fn4PysOdjIt0OnDbByC4eaRYVnJh33M#example.com>\r\nX-Mailer: PHPMailer 6.6.4 (https:\/\/github.com\/PHPMailer\/PHPMailer)\r\nMIME-Version: 1.0\r\nContent-Type: text\/html; charset=utf-8\r\n\r\n","test content\r\n"]
mailSendSingle: [{"Priority":null,"CharSet":"utf-8","ContentType":"text\/html","Encoding":"7bit","ErrorInfo":"","From":"me#mycompany.onmicrosoft.com","FromName":"John Doe","Sender":"me#mycompany.onmicrosoft.com","Subject":"test mail","Body":"test content","AltBody":"","Ical":"","WordWrap":0,"Mailer":"smtp","Sendmail":"\/usr\/sbin\/sendmail","UseSendmailOptions":true,"ConfirmReadingTo":"","Hostname":"","MessageID":"","MessageDate":"","Host":"smtp.office365.com","Port":"587","Helo":"","SMTPSecure":"tls","SMTPAutoTLS":true,"SMTPAuth":true,"SMTPOptions":{"ssl":{"verify_peer":false,"verify_peer_name":false,"allow_self_signed":true}},"Username":"","Password":"","AuthType":"XOAUTH2","Timeout":10,"dsn":"","SMTPDebug":2,"Debugoutput":"html","SMTPKeepAlive":false,"SingleTo":false,"do_verp":false,"AllowEmpty":false,"DKIM_selector":"","DKIM_identity":"","DKIM_passphrase":"","DKIM_domain":"","DKIM_copyHeaderFields":true,"DKIM_extraHeaders":[],"DKIM_private":"","DKIM_private_string":"","action_function":"","XMailer":""},{"from_mail":"me#mycompany.onmicrosoft.com","from_name":"John Doe","smtp_profile":3,"from_user":1,"to_mail":"me#example.com","to_name":"John Doe","to_type":"staff","to_id":3,"template":0,"debug":true,"testing":true,"subject":"test mail","type":"test","date":"2022-09-22 19:49:08","content":"test content","reply_to":"me#mycompany.onmicrosoft.com"},true]
mailSend: [{"from_mail":"me#mycompany.onmicrosoft.com","from_name":"John Doe","smtp_profile":3,"from_user":1,"to_mail":"me#example.com","to_name":"John Doe","to_type":"staff","to_id":3,"template":0,"debug":true,"testing":true,"subject":"test mail","type":"test","date":"2022-09-22 19:49:08","content":"test content","reply_to":"me#mycompany.onmicrosoft.com"}]
2022-09-22 17:49:08 CLIENT -> SERVER: QUIT
2022-09-22 17:49:08 SERVER -> CLIENT: 221 2.0.0 Service closing transmission channel
I know it's a lot of code but there isn't really much to say, I could ommit the whole token obtaining because it works. I assume the error lies somewhere in the azure configuration? The user I've obtained the token with is just a "member" (Role "Global administrator"), the "owner" of the app is another one.

using these options for the provider (in both places, aquiring token and sending mail) did it (it's the tenant id):
'urlAuthorize' => 'https://login.microsoftonline.com/b3095h58-5987-4489-a1dd-b132f2f38113/oauth2/authorize',
'urlAccessToken' => 'https://login.microsoftonline.com/b3095h58-5987-4489-a1dd-b132f2f38113/oauth2/token'
It seemed irrelevant whether to use windows.net or microsoftonline.com
However now I'm at the same point as described here. Funnily even using Thunderbird to test the oauth authentification fails for sending (receiving is fine though).

Related

OctoKit Ruby Authentication

I'm sure that this is a simple error, but I'm interested in writing a program that collects information on all of my github repositories. While this seems simple enough to do with Octokit, I've run into issues associated with authenticating my session.
client = Octokit::Client.new \
:login => 'MY_USER_NAME',
:password => 'MY_PASSWORD'
puts client
user = client.user("MY_USER_NAME", :headers => { "PERSONAL_ACCESS_TOKEN_NAME" => "TOKEN" })
puts user
Unfortunately this results in the following:
GET https://api.github.com/users/mccoleman75225: 401 - Must specify two-factor authentication OTP code. // See: https://developer.github.com/v3/auth#working-with-two-factor-authentication (Octokit::OneTimePasswordRequired)
How does someone go about authenticating their session?
As of January 2022, you can create a PAT (Personal Access Token) in your GitHub Developer Settings and use that to connect through the Octokit client like so:
client = Octokit::Client.new(:access_token => "<Your Personal Access Token>")
user = client.user
user.login
# => "monacat"
Here's a step-by-step guide on how to create a PAT. Try to select the correct permissions when creating your token or you'll get back a 403 error with a message explaining the missing scope. You can always go back and edit your scopes later though.
Sources:
Octokit.rb — Authentication
GitHub API Authentication - Personal Access Tokens
Looks like you have 2 Factor Authentication enabled on your account so you'll need to add your 2FA token:
client = Octokit::Client.new \
:login => 'defunkt',
:password => 'c0d3b4ssssss!'
client.create_authorization(:scopes => ["user"], :note => "Name of token",
:headers => { "X-GitHub-OTP" => "<your 2FA token>" })
# => <your new oauth token>
See documentation

Laravel mail - how to debug Mailgun

I'm trying to set up mailgun with laravel (5.3) but returns null, doesn't shows error and doesn't send email. Also i tried this mailgun params with PHP CURL, its working as well. Also i have set MAIL_DRIVER=log its working to. How i can debug Laravel Mailgun?
I have installed Guzzle.
I dont install Laravel Queue system. Can be problem because of this?
My log:
[2019-08-06 13:19:04] local.DEBUG: Message-ID:
<21f27....9cf293be62#todo.test>
Date: Tue, 06 Aug 2019 13:19:04 +0000
Subject: Activate Your Account
From: s....#gmail.com
To: s....#gmail.com
MIME-Version: 1.0
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable
<h2>this is test mail</h2>
<p>Lorem ipsum dolor sit amet, consectetur</p>
My .env params
MAIL_DRIVER=mailgun
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=2525 //tried other ports 25, 587, and 465
MAIL_USERNAME=postmaster#sandbox5....a6df0f425dfd0.mailgun.org
MAIL_PASSWORD=f6ae0....b4e0a8205b-73ae490d-d2e10d3d
MAIL_ENCRYPTION=TLS
MAILGUN_DOMAIN=sandbox.....f0f425dfd0.mailgun.org
MAILGUN_SECRET=56cc50b....10c62e08-73ae490d-11f1b30a
MAIL_FROM_ADDRESS=postmaster#sandb....df0f425dfd0.mailgun.org
MAIL_FROM_NAME=ToDo
My Contrller
Mail::to('m....r#gmail.com')->send(new SendMail());
if(count(Mail::failures()) > 0){
return 'Failed to send password reset email, please try again.';
}
My Mail class
public function build()
{
return $this->from('postmaster#san....0f425dfd0.mailgun.org')
->subject('Activate Your Account')
->view('emails.test');
}
I find problem, in config/services.php
'mailgun' => [
'domain' => 'https://api.mailgun.net/v3/sandbox53bb3c32cee7449f961a6df0f425dfd0.mailgun.org',
'secret' => '56cc50bafb9320f2ef3c9d3210c62e08-73ae490d-11f1b30a',
],
Changed to
'mailgun' => [
'domain' => 'sandbox53bb3c32cee7449f961a6df0f425dfd0.mailgun.org',
'secret' => '56cc50bafb9320f2ef3c9d3210c62e08-73ae490d-11f1b30a',
],
Then returns
Client error: `POST https://api.mailgun.net/v3/dfd0.mailgun.org/messages.mime` resulted in a `400 BAD REQUEST` response:
{
"message": "Sandbox subdomains are for test purposes only. Please add your own domain or add the address to authoriz (truncated...)
Eventually mailgun API works

Unable to authorize to a OAuth 2 legged provider

I am trying to authenticate to a 2 legged OAuth(1.0) system from ruby irb as follows using oauth ruby gem,
Step 1:
require 'oauth'
irb(main):038:0> consumer = OAuth::Consumer.new("key", "secret", :site => "site", :scheme => :query_string)
I got a response for this as,
=> #<OAuth::Consumer:0xba14be2c #key="{got valid key here}", #secret="{got valid secret here}", #options={:signature_method=>"HMAC-SHA1", :request_token_path=>"/oauth/request_token", :authorize_path=>"/oauth/authorize", :access_token_path=>"/oauth/access_token", :proxy=>nil, :scheme=>:query_string, :http_method=>:post, :oauth_version=>"1.0", :site=> "https://example.com/">
Step 2:
irb(main):039:0> access_token = OAuth::AccessToken.new consumer
=> #<OAuth::AccessToken:0xba144b7c #token="", #secret="", #consumer=#<OAuth::Consumer:0xba147430 #key="{got valid key here}", #secret="{got valid secret here}", #options={:signature_method=>"HMAC-SHA1", :request_token_path=>"/oauth/request_token", :authorize_path=>"/oauth/authorize", :access_token_path=>"/oauth/access_token", :proxy=>nil, :scheme=>:query_string, :http_method=>:post, :oauth_version=>"1.0", :site=>"https://example.com/"}>, #params={}>
Please see Token is empty above. I should have got the token here??
Step 3: Then i tried all the paths which i got from above,
irb(main):041:0> access_token.get("/oauth/authorize")
irb(main):041:0> access_token.get("/oauth/request_token")
irb(main):041:0> access_token.get("/oauth/access_token")
But for all the request am getting response as,
=> #<Net::HTTPNotFound 404 Not Found readbody=true>
I dono where i am making mistake, am i doing the request correctly, if not how should i authenticate to the 2legged oauth system in ruby. Or should i ask the service provider to check on their side.
Token field is empty in step 2, that is the problem??.
Can anyone please guide me in this?? Thanks in advance.
maybe this code will help:
require 'oauth'
consumer_key = <your consumer key>
consumer_secret = <your consumer secret>
end_point = "https://www.example.com"
consumer = OAuth::Consumer.new(consumer_key, consumer_secret, {
:site => end_point,
:scheme => :header
})
parameters = "user_id=1"
resp = consumer.request(:post, '/get_user/', nil, {}, parameters, { 'Content-Type' => 'application/x-www-form-urlencoded' })

Can't connect to exchange server to send mail via SMTP in ruby

I have tried everything I can think of. I have tried with all authentication types I can think of.
here are my settings
delivery_method :smtp, {
:address => "xxxxxxxxx.com",
:port => port,
:domain => 'xxxxxx.com',
:user_name => 'username',
:password => "passworde",
:authentication => 'plain',
:enable_starttls_auto => true }
here is my error if I use port 25 (I believe this to be the correct port)
c:/Ruby193/lib/ruby/1.9.1/net/smtp.rb:960:in `check_auth_response': 504 5.7.4 Unrecognized authentication type (Net::SMTPAuthenticationError)
here is my error if I use port 587
c:/Ruby193/lib/ruby/1.9.1/openssl/ssl-internal.rb:121:in `post_connection_check': hostname does not match the server certificate (OpenSSL::SSL::SSLError)
The hash you're passing should have :plain defined as a symbol rather than a string per the ActionMailer::Base docs. The server is definitely responding on port 25 (that 504 5.7.4 Unrecognized authentication type error is from the server) so stick with that port.
It's also probably that plain auth is disabled on your server. Check out Cannot get ActionMailer working with MS Exchange via SMTP for more info.

How to create user on domain with Google apps marketplace API?

We have application published with Google apps marketplace. we need to create user on domain where they install our app through API. I have tied the following php code but, i am getting 401 error. Please help.
$oauthOptions = array(
'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
'version' => '2.0', 'scope' => '',
'signatureMethod' => "HMAC-SHA1",
'consumerKey' => 'marketplace oauth consumer key',
'consumerSecret' => 'marketplace oauth consumer secret key' );
$consumer = new Zend_Oauth_Consumer($oauthOptions);
$token = new Zend_Oauth_Token_Access();
$token->setToken('');
$token->setTokenSecret('');
$client = $token->getHttpClient($oauthOptions);
$gdata = new Zend_Gdata_Gapps($client, 'domain name');
$gdata->createUser('user34', 'fistname', 'familyname', 'Password');
You're using the wrong OAuth version - the consumer key and secret work with 1.0, not 2.0. You also don't need to set the scope, token, or token secret to empty strings but I'm not certain whether that would actually cause any problems.
There's a working example of doing two-legged OAuth in PHP at http://code.google.com/p/google-mail-xoauth-tools/source/browse/trunk/php/two-legged.php. It isn't a marketplace application but the authentication is the same so it should be a good starting point.

Resources