Google Analytics Service API - Determining if access token is expired - oauth

I am wondering if anyone knows a clean programmatic way of detecting a 401 response with the analytics API. I know the underlying HTTP transport probably has it but when the call is made via Analytics object the only indicator of failure is an IOException (which could indicate an error of any type). If there was some way to get at the JSON response that gets shown in the stack trace you could check there maybe, but right now the only thing I can think of is to parse the e.getMessage() string. Example:
GaData gadata = null;
try {
gaData = analytics.data().ga().get(
"ga:" + profileId,
"2012-06-01",
"2012-06-30",
"ga:visits")
.execute();
} catch (IOException ioe) {
if (ioe.contains("401")) {
System.out.println("A 401 occurred.");
}
}
The reason for isolating this case is because it indicates that the access token has expired, so an alternate solution would be a better way for checking if the access token has expired. If this can be done then the code can make a call using the API key to grant a new access token.

The documentation says that the GoogleJsonResponseException will be thrown. GoogleJsonResponseException.getDetails() returns a GoogleJsonError. The GoogleJsonError.code method will return the error code (in this case the HTTP 401 ERROR).

Related

Twilio catch exception while creating client object

I'm trying to check that Twilio object was properly instantiated, but it doesn't work
I do
try {
$twilioObj = new Client($sid, $token);
}
catch (Exception $e){
echo $e->getMessage();
}
^ Regardless if the tokens are valid or not it never results in an error. I noticed that it always generated an object.. So even if I put some random token, I still get an object back.
What is the best way of catching this?
I did is as per documentation: https://www.twilio.com/docs/libraries/php/usage-guide#exceptions but it doesn't work.
The Twilio Client object doesn't know at the time of instantiation whether the credentials you have provided it are valid or not, so it cannot throw an error at that point.
If the credentials are not valid, the client will throw an error when you use it to make a request to the API. You should catch the error there.
As per the documentation, instantiating a Client without a username or password will throw a ConfigurationException.

How to detect errors from GraphServiceClient SendMail

I am using the following code to send email for the logged in user.
await _graphClient.Me.SendMail(email, true).Request().PostAsync();
Initially it was executing be no email was sent. After poking around I figured out that a permission was not set. Unfortunately the try..catch around it was not tripped. My questions is if there is a way of detecting that an error occurred with this call.
Regarding
Unfortunately the try..catch around it was not tripped.
PostAsync() method should throw a ServiceException on error.
For example, in case of missing permissions:
try
{
await graphClient.Users[userId].SendMail(message).Request().PostAsync();
}
catch (Microsoft.Graph.ServiceException e)
{
Console.WriteLine(e.Error);
}
the following error should be printed:
Code: ErrorAccessDenied
Message: Access is denied. Check credentials and try again.

Twilio Invalid Access Token Signature (iOS - Swift)

I am using Twilio's latest SDK they released on CocoaPods as of today. I am trying to implement VOIP feature to my app with Twilio Programmable Voice. My backend is .net which also uses the latest release of Twilio Helper Library for C#.
My client code looks like:
fetchAccessToken { (accessToken: String) in
TwilioVoice.register(withAccessToken: accessToken, deviceToken: deviceToken) { (error) in
if let error = error {
NSLog("An error occurred while registering: \(error.localizedDescription)")
}
else {
NSLog("Successfully registered for VoIP push notifications.")
}
}
}
What I get in the console is as following:
voipTestWithTwilio[2431:517236] [ERROR TwilioVoice] Inside register:deviceToken:completion:, failed to register for Twilio push notifications. Error:Invalid access token signature
voipTestWithTwilio[2431:517236] An error occurred while registering: Invalid access token signature
This is the C# code that actually creates the token:
var grant = new VoiceGrant
{
OutgoingApplicationSid = outgoingApplicationSid
};
var grants = new HashSet<IGrant> { { grant } };
var token = new Token(
accountSid: accountSid,
signingKeySid: apiKey,
secret: apiSecret,
identity: identity,
grants: grants
);
return token.ToJwt();
I have been looking for the issue on the internet, nothing helped so far. I have tried contacting them but have not got any response back. I also tried creating new api keys and even a new project for a couple times on Twilio. Can anybody say something about the issue?
UPDATE
I added push notification sid to VoiceGrant and now I’m getting 403 Forbidden.
On Twilio error codes page it is explained as: “The expiration time provided in the Access Token exceeds the maximum duration allowed.” which is definitely not my case. However, I tried passing expiration parameter in Token constructor with various values which didn’t change the result.
The problem is still persisting.
I solved the issue. It was because my server returned the token with quotation mark.
I remember print(token)'ing on client (iOS) to see whether there is encoding issue or something and all I see was a proper token between quotation marks. Since token is a string value, I didn't pay attention to quotation part of it. That's where I was wrong.

Incomplete Linkedin OAuth 2.0 access token response

My question is about OAuth2 access token response from Linkedin api. When I'm trying to get this token I recieve the following response:
{"access_token":"...","expires_in":...}
But the thing is that according to OAuth2 documentation (in 5.1 paragraph) there should be at least one more required parameter - "token_type".
So the question is: could it be somehow customized so the linkedin API will return this parameter with access token response or it is just a departure from the rule and this parameter won't be returned?
Thanks in advance.
I have run into the same issue. According to LinkedIn Docs:
A successful Access Token request will return a JSON object containing the following fields:
access_token — The access token for the user. This value must be kept secure, as per your agreement to the API Terms of Use.
expires_in — The number of seconds remaining, from the time it was requested, before the token will expire. Currently, all access tokens are issued with a 60 day lifespan.
they respond with
{"access_token":"...","expires_in":...}
which violates the standard.
Currently I am using Spring Security 5.0.3 and to fix the issue, I had to monkeypatch one class:
com.nimbusds.oauth2.sdk.token.BearerAccessToken
I will not post the whole class, only a significant part:
public static BearerAccessToken parse(final JSONObject jsonObject)
throws ParseException {
// Parse and verify type
AccessTokenType tokenType;
try {
tokenType = new AccessTokenType(JSONObjectUtils.getString(jsonObject, "token_type"));
} catch (ParseException ex) {
tokenType = AccessTokenType.BEARER;
}
if (!tokenType.equals(AccessTokenType.BEARER))
throw new ParseException("Token type must be \"Bearer\"");
//...
}
I hoped to get answer from Linkedin member since they stated on their site that stackoverflow is a proper place for asking such questions. But since there is no answer from them and I didn't find any relevant information regarding this question I believe that it is just the way they implemented OAuth 2.0 protocol.

Able to POST direct messages using Twitter's REST API, but trying to GET returns a 401 error

I am trying to get direct messages working in my app. I'm able to POST DMs just fine, but when I try to GET them from the endpoint https://api.twitter.com/1.1/direct_messages.json it returns a 401 - Unauthorized. I don't really understand how I can be authorized to send DMs but not get ones sent to me.
Here's how I'm authenticating initially:
if Twitter.sharedInstance().sessionStore.session() == nil {
Twitter.sharedInstance().logInWithCompletion { session, error in
if (session != nil) {
// successfully logged in, call loading functions
} else {
print("error: \(error!.localizedDescription)")
}
}
} else {
// already logged in, call loading functions
}
Every time I make a request using the REST API, it begins with
if let userID = Twitter.sharedInstance().sessionStore.session()?.userID {
let client = TWTRAPIClient(userID: userID)
The client is initialised the same way in both the POST and GET requests for DMs, yet the GET request fails.
As far as permissions go, I've checked that it has read/write/DM access according to Twitter, and successful requests return "x-access-level" = "read-write-directmessages";, so I think it's set properly.
I was concerned at one point that I might not be authenticating properly, since Twitter's documentation goes through the 3 step process for O-Auth and all I'm doing is telling the Twitter singleton to just log in... but I rationalised that away by assuming that those steps are all carried out in the logInWithCompletion function. And besides, if I wasn't authenticated properly I surely wouldn't be able to send DMs, right?
Any ideas on how I can fix this? I'm quite new so it may be something nice and simple! I've looked through some other questions, but they all seem to code the requests in full rather than using built-in methods like these - or have I got it all wrong?
Yeah, it was a stupid problem - I left the parameters blank since they are all marked as 'optional' - as in, a dictionary of ["" : ""]. I just set the paramaters in the request to nil, and now it works.

Resources