I hope this makes sense. I am using the Zoho C# SDK examples to write records to the CRM Leads. While calling recordOperations.CreateRecords(); it fails after trying to GetToken from the Token Store.
Here is the token I am saving
Token token = new OAuthToken(
"xxxx.clientid.goes.here.xxxxx",
"xxxx.clientsecret.goes.here.xxxx",
"REFRESH/GRANT token",
TokenType.GRANT,
string.Empty);
TokenStore tokenStore = new CustomTokenStore();
tokenStore.SaveToken(user, token);
And I am sending this token into the SDKInitilizer.Initialize. No errors at this point. Next I try and create a lead. When it gets inside of recordOperations.CreateRecords(); it tries GetToken and I've hard coded it to return exactly what was in the token object above. CreateRecords throws an error for "invalid_code". Here is what is in the log file
21-09-07 16:49:34 [INFO]: Initialization successful for Email Id : myemail#email.com in Environment : https://www.zohoapis.com.
21-09-07 16:49:47 [INFO]: Access Token has expired. Hence refreshing.
21-09-07 16:49:50 [ERROR]: Exception in authenticating current request : {"Code":"INVALID CLIENT ERROR","Message":"invalid_code","Cause":null,"Details":null,"StackTrace":" at Com.Zoho.API.Authenticator.OAuthToken.ParseResponse(String response)\r\n at Com.Zoho.API.Authenticator.OAuthToken.RefreshAccessToken(UserSignature user, TokenStore store)\r\n at Com.Zoho.API.Authenticator.OAuthToken.Authenticate(APIHTTPConnector urlConnection)\r\n at Com.Zoho.Crm.API.Util.CommonAPIHandler.APICall[T](Type className, String encodeType)","Data":{},"InnerException":null,"HelpLink":null,"Source":"ZCRMSDK","HResult":-2146233088}
It appears to be failing when it tries to refresh the token so I assume I am not sending in the right info in the token object?
*** Edit for #sucasa ***
This is what I am sending into the Initialize method.
What I have figured out since my first post is, I'm not getting the initial token from Initialize and its not calling the custom TokenStore.SaveToken() I created and it should, right? If I save it, all I have is what is above, not an actual token. So I think when I go to create the lead, I don't actually have the initial token to refresh. I hope that's clearer.
Access Tokens expire and must be refreshed using a refresh token. The error message indicates this. Can you log the value of token and report back here?
Related
I have a web app which utlizes Oauth and is unable to reuse the authToken due to the error below.
{"AADSTS70002: Error validating credentials. AADSTS54005: OAuth2 Authorization
code was already redeemed, please retry with a new valid code or use an
existing refresh token.\r\nTrace ID: 30c342a7-f16a-4a05-a4a8-
c7ee2c722300\r\nCorrelation ID: 3a5c99d1-ca1c-4cd7-bd36-
cce721bf05b6\r\nTimestamp: 2018-11-21 00:26:18Z"}
I'm told this is a know issue/update here and here.
...okay, fine so now I'm trying to get the refresh token so I can regenerate my access token but I'm having trouble getting something to work.
I have tried the ones below:
https://learn.microsoft.com/en-us/bingads/shopping-content/code-example-authentication-oauth - this one does not seem to work and throws an exception when I try to get the accesstoken or refresh token. stating that one or more errors have occured.
https://auth0.com/docs/api/authentication#authorization-code-pkce- - but does not return the refresh token. Could this be because I don't have the code_verifier? If so, how would I get that?
Authorization Code (PKCE) Image
Below is a code sample which I am using - problem here is that I can only use this once and once It has been redemed I cannot retrive it silently as it no longer exists in the cache.
ClientCredential clientcred = new ClientCredential(Constants.ClientId, Constants.AppKey);
TokenCache TC = new TokenCache();
AuthenticationContext AC = new AuthenticationContext(Constants.Authority, TC);
//Set token from authentication result
AuthenticationResult authenticationResult = await AC.AcquireTokenByAuthorizationCodeAsync(
Constants.Code,
new Uri(Constants.postLogoutRedirectUri + "Index"), clientcred);
return authenticationResult.AccessToken;
You need to call OAuth2 authorize endpoint with offline_access scope to get refresh token.
You should call AcquireTokenByAuthorizationCodeAsync only once when you receive authorization code and should not use the result. azure ad sample
You need to call AcquireTokenSilently when you want to get access token. azure ad sample
This azure ad sample use a TokenCache implementation by user id.
Authorize request
Token request
Good luck!
I have been integrating QuickBooks's API to my web application. I made requests to get tokens (both request token and secret token), I stored them to database. So, how can I validate connection at second time or more, I mean because I had tokens in database, so I don't want to re-authorize to get other new tokens. I tried to find solutions to resolve it, but there's no anything. Please give me some methods or advices to get it done. Thank you very much!
So, how can I validate connection at second time or more,
You can validate tokens by doing a query against a v3 service, and checking to see if you get a 200 OK or a 401 Unauthorized response back.
Pseudo-code should look something like this:
function am_i_connected_to_quickbooks()
{
if (you have tokens stored in your database)
{
results = do_qb_query("SELECT * FROM Customer MAXRESULTS 1")
if (you got a 200 OK back from Intuit)
{
// You are connected, and the tokens are still valid/have not been revoked
return true
}
}
// You don't have tokens, or your tokens are invalid (revoked, expired, incorrect, etc.)
return false
}
I've been attempting to process a very simple express checkout Sandbox transaction using the C# Paypal API, but keep getting a session timeout error on the Paypal website after the redirect.
I should emphasize that I get a successful ACK response from SetExpressCheckout along with a Token string.
Here is an example of the checkout URL I've been trying to redirect to:
https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-9RY2628262462061J
My return address is localhost, but I couldn't see anywhere that this would be a problem in Sandbox.
On trying to redirect to the Sandbox I arrive not at the checkout URL but at this address:
https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_flow&SESSION=CzvBHQErPEHw5gOt51FV88G_4L9HUCLypeGkwVZLW6mkWsZOofIpFR2K6Aa&dispatch=50a222a57771920b6a3d7b606239e4d529b525e0b7e69bf0224adecfb0124e9b61f737ba21b081984719ecfa9a8ffe80733a1a700ced90ae
And see the following error message:
"This transaction has expired. Please return to the recipient's website to complete your transaction using their regular checkout flow."
How can the transaction be timing out when [1] I have a successful API response along with a token and [2] I literally redirect there immediately after getting the token.
Does anyone have any idea what's going on here?
If it helps here is the C# I wrote to access the API. As noted, I get a success ACK response plus a token.
try
{
var details = ToPaymentDetails(data);
var request = new SetExpressCheckoutReq();
request.SetExpressCheckoutRequest = new SetExpressCheckoutRequestType
{
SetExpressCheckoutRequestDetails = details,
Version = Version
};
var result = await client.SetExpressCheckoutAsync(credentials, request);
var response = result.SetExpressCheckoutResponse1;
FailOnError(response);
return Result.Success(response.Token);
}
catch (Exception ex)
{
return Result.Error<string>("Received an error from Paypal.SetExpressCheckout.", exception: ex);
}
The EC token only last for 3 hours. You will have to recall the SetEC API to get a new EC token and proceed with the checkout flow.
I am not closer to understanding why the SOAP API call generates a token that is rejected by Paypal, but I found that I was able to reach the Sandbox payment page if I used the SDK to generate a payment.
This hasn't exactly been an enlightening or educational experience ...
I have some JavaScript that logs in a Facebook user and saves the access token to a database:
window.fbAsyncInit = function () {
FB.init({
appId: '<%=FaceBookApplicationId() %>',
status: false, // check login status
cookie: true,
oauth: true
});
};
function facebookLogin() {
FB.login(function(response) {
if (response.authResponse) {
__doPostBack('__Page', 'FacebookDeliveryButton: ' + JSON.stringify(response.authResponse));
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, { scope: 'offline_access,read_stream,publish_stream,user_photos' });
}
A button click fires facebookLogin() which logs in a facebook user, getting a facebook session that includes an access token, which I JSON serialize and post to the server. The server then saves this access token to the database table FacebookDeliveryQueue.
I have a Windows service running that periodically queries the FacebookDeliveryQueue table and attempts to post on a user's wall using the access token we saved earlier:
IQueryable<FacebookDeliveryQueue> toSend = objectContext.FacebookDeliveryQueues.Where(p => !p.IsDelivered);
foreach (FacebookDeliveryQueue facebookDeliveryQueueItem in toSend)
{
string facebookAccessToken = facebookDeliveryQueueItem.Cart.FacebookAccessToken;
string facebookRecipientId = facebookDeliveryQueueItem.Cart.FacebookRecipientId;
var client = new FacebookClient(facebookAccessToken);
dynamic parameters = new ExpandoObject();
parameters.message = facebookDeliveryQueueItem.Cart.CustomMessageBody;
client.Post(facebookRecipientId + "/feed", parameters);
}
My problem is, this ONLY works with access tokens from the user that created the facebook application. E.g.
Success:
I, the creator of this application, log in and pick one of my friends to send a message to, this info is saved to the database, the service runs, my message is posted to my friend's wall.
Failure:
I log in on my dummy test account (approving the app permissions on this account), pick one of my dummy test account's friend, this info is saved to the database, the service runs and throws an invalid access token error.
Any ideas why?
Update: Switched to Oauth login -- no change. Still getting "(OAuthException) Invalid access token signature." when attempting to post to friend's wall.
Looks like you're using facebook's old login methods, which they recently just turned off, so your old access tokens aren't valid anymore? And your javascript isn't generating the right kind of token. Read the latest version of the FB.login documentation for more info on what changes you need to make. Specifically,
pass oauth: true to the FB.init call
check for response.authResponse instead of response.session now.
Also, check that your app isn't in "sandbox mode". Go to the app settings page and click on "advanced". Sandbox mode makes it so that only developers can use the app.
The persistence to the database was silently trimming the access token to 75 characters, which in the case of my own user, was enough (small user id because it's an old account) -- but five characters too short in the case of my test account which has a very large user id.
Woops.
I am connecting to login facebook page through an url. I receive the access token in my application and i can prints all my contacts from the list. I have a problem: there are times when i do receive the access token and if i logout from facebook and rebuild my application the second time , i don't have any access token. WHY? If i wait i guess 10-15 minutes and try again it works. How to resolve this? THX
I am using the auth url. THe following link was my example link:
http://geekdeck.com/vb-net-facebook-get-access-token-for-desktop-application/
EDIT:
I have the following code:
browserFacebook.Navigate(#"https://graph.facebook.com/oauth/authorize?client_id="+ FacebookApplicationID + "&redirect_uri=http://www.facebook.com/connect/login_success.html&type=user_agent&display=popup");
string someString = browserFacebook.Url.ToString();
This returns something like the following:
"http://www.facebook.com/connect/login_success.html#access_token=ACCESS TOKEN.expires_in=0"
I can then easily use this access token with the Graph API to access an users facebook details as in the following code:
Facebook.FacebookGraphAPI g = new FacebookGraphAPI("ACCESS_TOKEN");
var fbUser = g.GetObject("me", null);
PROBLEM:
When I rebuild the application, the link that i receive is OpenDNS (or navigation to the webpage was canceled) and I have to access token. Why? How can I resolve this error? After a a while 1-2 hours I receive again the token.
"https://graph.facebook.com/oauth/authorize?client_id=" +
FacebookApplicationID +
"&redirect_uri=http://www.facebook.com/connect/login_success.html&type=user_agent&display=popup");