Xero-Api PHP Authentication Unsuccessful when refreshing token - refresh-token

I am having issues with refreshing tokens with the xero api. When I first create the token, everything is fine. When I refresh the token, I get authentication unsuccessful.
{"Type":null,"Title":"Forbidden","Status":403,"Detail":"AuthenticationUnsuccessful","Instance":"8d6256e5-3376-4960-be52-cf8b22ee241c","Extensions":{}}
My code is as follows:
public function refreshToken()
{
$provider = new GenericProvider([
'clientId' => $valuestore->get('client_id'),
'clientSecret' => $valuestore->get('client_secret'),
'redirectUri' => $valuestore->get('callback_url'),
'urlAuthorize' => 'https://login.xero.com/identity/connect/authorize',
'urlAccessToken' => 'https://identity.xero.com/connect/token',
'urlResourceOwnerDetails' => 'https://api.xero.com/api.xro/2.0/Organisation'
]);
$newAccessToken = $provider->getAccessToken('refresh_token', [
'refresh_token' => $this->getRefreshToken()
]);
// Save my token, expiration and refresh token
$this->setOauth($newAccessToken);
}
public function setOauth($accessToken)
{
$oauth2 = [
'token' => $accessToken->getToken(),
'expires' => $accessToken->getExpires(),
'tenant_id' => $this->getTenantId(),
'refresh_token' => $accessToken->getRefreshToken(),
'id_token' => $accessToken->getValues()["id_token"]
];
//set session
}
Thanks in advance
Regards
Danny

Related

Webklex\PHPIMAP Modern Auth Not Working 365

As with most people, Microsoft are turning off basic authentication. This means we need to use Modern Auth to retrieve emails from a mailbox.
However,when we retrie the access token fails with "
Client error: `POST https://login.microsoftonline.com/aea9a7d8-73fb-41af-987b-6fe14277421e/oauth2/v2.0/token` resulted in a `400 Bad Request` response:\n
{"error":"unauthorized_client","error_description":"AADSTS700016: Application with identifier '\"014438b9-82dc-4a4c-9584 (truncated...)
"
Here is the code we have for retrieving and connecting to IMAP. I am passing actual email and password in usename and password field
/* Get the access Token */
$Secret = '**REMOVED**';
$AppID = '**REMOVED**';
$TenantID = '**REMOVED**';
$AccessToken = '';
try {
$guzzle = new \GuzzleHttp\Client(['headers' => ['User-Agent' => 'App-Token-Request']]);
$url = 'https://login.microsoftonline.com/'.$TenantID.'/oauth2/v2.0/token';
$token = json_decode($guzzle->post($url, [
'form_params' => [
'grant_type' => 'password',
'client_id' => $AppID,
'client_secret' => $Secret,
'scope' => 'https://graph.microsoft.com/.default', //'https://outlook.office365.com/IMAP.AccessAsUser.All',// 'https://graph.microsoft.com/.default',
'username' => '**REMOVED**',
'password' => '**REMOVED**',
],
])->getBody()->getContents());
$this->info(var_dump($token));
$AccessToken = $token->access_token;
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
dd($e);
return redirect('/')->with('error', 'Error requesting access token')->with('errorDetail', json_encode($e->getResponseBody()));
}

New calendar event, created using Google service account isn't sending invitaion email to the attendees

I am creating a new event in Google Calendar by using Google's service account, and I have also set sendNotifications to true, but after creating an event, invitation emails are not sending to the attendees ??
# new event to be created
event = {
'summary'=> summary,
'description'=> description,
'start'=> {'dateTime' => datetime },
'end' => {'dateTime' => datetime },
'sendNotifications' => true,
'sequence' => sequence,
'reminders' => {
'useDefault' => false,
'overrides' => [
{'minutes' => 60, 'method' => 'email'}
]
},
'attendees'=> [
{
'email'=> email
}
]
}
# build client
client = Google::APIClient.new application_name: "Test", application_version: "0.0.1"
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/calendar',
:issuer => ENV['SERVICE_ACCOUNT_EMAIL'],
:grant_type => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
:access_type => 'offline',
:signing_key => key
)
# fetch access token
client.authorization.fetch_access_token!
# create new event
service = client.discovered_api('calendar', 'v3')
client.execute(:api_method => service.acl.insert,
:parameters => {'calendarId' => 'primary'},
:body => JSON.dump(event),
:headers => {'Content-Type' => 'application/json'})
sendNotifications is a property of the request, not of an event. See the documentation of an insert here: https://developers.google.com/google-apps/calendar/v3/reference/events/insert You can also try the explorer to see how exactly requests should look like: https://developers.google.com/apis-explorer/#p/calendar/v3/ (don't forget to authenticate in the top right corner).

Invalid authorization name/value {x-li-auth-token}/{NAME_SEARCH:tdLy}

Im working on LinkedIn invitation API but I can't send the invitation to user, using people id from search result
Seached people result
**
"{\"people\":{\"total\":2,\"all\":[{\"api_standard_profile_request\":{\"headers\":{\"total\":1,\"all\":[{\"name\":\"x-li-auth-token\",\"value\":\"NAME_SEARCH:tdLy\"}]},\"url\":\"http://api.linkedin.com/v1/people/tp2Z82Xa_I\"},\"first_name\":\"Dev\",\"id\":\"tp2Z8sad2Xa_I\",\"last_name\":\"ruby\"},{\"api_standard_profile_request\":{\"headers\":{\"total\":1,\"all\":[{\"name\":\"x-li-auth-token\",\"value\":\"NAME_SEARCH:ZbY6\"}]},\"url\":\"http://api.linkedin.com/v1/people/TyaEtFbxzL\"},\"first_name\":\"dev\",\"id\":\"TyaEtFbsdsaxzL\",\"last_name\":\"ruby\"}]}}"**
And the invite methods following this
def send_invitation(options)
path = "/people/~/mailbox"
message = {
"recipients" => {
"values" => [
{
"person" => {
"_path" => "/people/id=#{options[:email]}",
"first-name" => options[:first_name],
"last-name" => options[:last_name]
}
}]
},
"subject" => "Invitation to connect.",
"body" => options[:body],
"item-content" => {
"invitation-request" => {
"connect-type" => "friend",
"authorization" => {"name" => "x-li-auth-token","value" => "NAME_SEARCH:tdLy"}
}
}
}
post(path, MultiJson.dump(message), "Content-Type" => "application/json")
end
So I am getting this error when I call client.send_invitation(options):
LinkedIn::Errors::GeneralError: (400): Invalid authorization name/value {x-li-auth-token}/{NAME_SEARCH:tdLy}
Working Fine
The name should be NAME_SEARCH and the value should be tdLy instead of what i have asked above. i have to split the value out of the oauth headers.
"authorization" => {:"name" => 'NAME_SEARCH',:"value" => 'tdLy'}

Yahoo OAuth 1.0 Callback Issue?

I want to use Yahoo Fantasy sport API in my web application, For that I am using OAuth for Yahoo login. I have consumer key and secret key and i passed the keys successfully, When I run the following code. It redirects to Yahoo login, It asks permission for accessing the user's credentials. If i give AGREE the page Redirects to https://api.login.yahoo.com/oauth/v2/request_auth and It shows the Verifying code. If i press the close button in verification code page, it's not callback to my URL.
#ts=Time.now.to_i
#callback_url = "http://localhost:3000/callback"
#nonce = SecureRandom.hex()
consumer = OAuth::Consumer.new("my consumerkey","secret key",
{ :site => 'https://api.login.yahoo.com',
:http_method => :post,
:scheme => :header,
:oauth_nonce => #nonce,
:request_token_path => '/oauth/v2/get_request_token',
:authorize_path => '/oauth/v2/request_auth',
:access_token_path => '/oauth/v2/get_token',
:oauth_callback => "http://localhost:3000/callback",
:oauth_timestamp => Time.now.to_i,
:oauth_signature_method => "HMAC-SHA-1",
:oauth_version => "1.0",
:oauth_callback_confirmed => true,
})
request_token = consumer.get_request_token
session[:request_token]=request_token
redirect_to request_token.authorize_url
access_token=request_token.get_access_token
access = ActiveSupport::JSON.decode(access_token.to_json)
if !(access.present?)
#response = "Response failed"
else
#response = access
end
Can you please tell me What changes to be made to get the callback for to get access_token.
I think you got confused while getting callback. change your code as follows, You will surely get access token to make Yahoo API call.
##access_token = nil
##request_token = nil
def get_request_token
##consumer = OAuth::Consumer.new('consumer key',
'secret key',
{
:site => 'https://api.login.yahoo.com',
:scheme => :query_string,
:http_method => :get,
:request_token_path => '/oauth/v2/get_request_token',
:access_token_path => '/oauth/v2/get_token',
:authorize_path => '/oauth/v2/request_auth'
})
##request_token = ##consumer.get_request_token( { :oauth_callback => 'http://localhost:3000/callback' } )
session[:request_token]=##request_token
redirect_to ##request_token.authorize_url
#redirect_to ##request_token.authorize_url( { :oauth_callback => 'http://localhost:3000/success' } )
end
def callback
request_token = ActiveSupport::JSON.decode(##request_token.to_json)
if !(request_token.present?)
$request_token_value = "Response failed"
else
$request_token_value = request_token
end
# access_token = ##request_token.get_access_token({:oauth_verifier=>params[:oauth_verifier],:oauth_token=>params[:oauth_token]})
##access_token = ##request_token.get_access_token(:oauth_verifier=>params[:oauth_verifier])
access_json = ActiveSupport::JSON.decode(##access_token.to_json)
puts "****************************"
puts $access_json
puts "****************************"
end

Google Calendar Service Account API leads to invalid grant

I have took the sample code from
http://code.google.com/p/google-api-ruby-client/source/browse/service_account/analytics.rb?repo=samples
however, I have been trying to get it working but it just keeps on giving, no matter how hard I try ! Here is the error I keep on getting
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/signet-0.4.5/lib/signet/oauth_2/client.rb:875:in `fetch_access_token': Authorization failed. Server message: (Signet::Authorization
Error)
{
"error" : "invalid_grant"
}
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/signet-0.4.5/lib/signet/oauth_2/client.rb:888:in `fetch_access_token!'
How Do I solve this ?
Here is my complete code
require 'google/api_client'
require 'date'
require 'openssl'
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
# Update these to match your own apps credentials
service_account_email = 'xxxxxx' # Email of service account
key_file = 'privatekey.p12' # File containing your private key
key_secret = 'notasecret' # Password to unlock private key
profileID = 'xxxxx' # Analytics profile ID.
client = Google::APIClient.new()
# Load our credentials for the service account
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
:issuer => service_account_email,
:signing_key => key)
# Request a token for our service account
client.authorization.fetch_access_token!
analytics = client.discovered_api('analytics','v3')
startDate = DateTime.now.prev_month.strftime("%Y-%m-%d")
endDate = DateTime.now.strftime("%Y-%m-%d")
visitCount = client.execute(:api_method => analytics.data.ga.get, :parameters => {
'ids' => "ga:" + profileID,
'start-date' => startDate,
'end-date' => endDate,
'dimensions' => "ga:day,ga:month",
'metrics' => "ga:visits",
'sort' => "ga:month,ga:day"
})
print visitCount.data.column_headers.map { |c|
c.name
}.join("\t")
visitCount.data.rows.each do |r|
print r.join("\t"), "\n"
end
I have spent whole day to get this working. Please help. Thanks for your time.
Solved it !
My Computer clock was for some reason 4 hours late ! Corrected System Time, it lead to no error.
1 - Make Your you solve the SSL Error if you have any by using the Google API Faq.
It took me whole day, so I'm going to leave my solutions so in future no one has to go crazy like I did.
account_email = '#developer.gserviceaccount.com'
key_file = 'privatekey.p12'
key_secret = 'notasecret'
client = Google::APIClient.new()
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/calendar',
:issuer => account_email,
:signing_key => key)
# # Request a token for our service account
client.authorization.fetch_access_token!
service = client.discovered_api('calendar', 'v3')
Example to execute something shall be like in similar fashion.
#event = {
'summary' => '',
'location' => 'this is where the location goes',
'description' => 'desc',
'start' => {
'dateTime' => '2013-02-08T10:00:00.000-07:00' # Date with :- offset so (yyyy-mm-dd T hh:mm:ss.000-offset)
},
'end' => {
'dateTime' => '2013-02-08T10:25:00.000-07:00' # Date with :- offset so (yyyy-mm-dd T hh:mm:ss.000-offset)
}
}
# Create event using the json structure
result = client.execute(:api_method => service.events.insert,
:parameters => {'calendarId' => '**'},
:body => JSON.dump(#event),
:headers => {'Content-Type' => 'application/json'})

Resources