"Access Denied" error on Google Auth API for Calendar - asp.net

I have been trying since yesterdar to authenticate my requests to de Google Calendar V3 API in order to use it, but I am unable to pass through an AggregateException which contains just the text "Access Denied".
My conflictive code is this, being the last line the one who breaks:
UserCredential credential;
using (var stream =
new FileStream(HostingEnvironment.MapPath(credentialsPath), FileMode.Open, FileAccess.Read))
{
string credPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, writePath);
var authTask = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)
);
credential = authTask.Result;
}
I have already tried recreating the secret key, generating the client_secret.json file again, creating another credentials... also I know that both paths, the JSON and the folder are correct, because I had to solve that before reaching this error.
Any hints on what can be the problem?
Thanks!

"Access Denied" error is usually encountered due to Invalid Credentials.
Here are the suggested actions that you can try:
Get a new access token using the long-lived refresh token.
If this fails, direct the user through the OAuth flow, as described in Authorizing requests with OAuth 2.0.
If you are seeing this for a service account, check that you have successfully completed all the steps in the service account page.
Hope that helps!

Related

REST API Getting 401 UnAuthorized

I am using .NET Core Web API to make call and getting back
401, unauthorized ? I am using a REST API key.
var ApiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var _Http = new HttpClient();
var response = await _Http.GetAsync($"https://geocode.search.hereapi.com/v1/geocode?q={address},{city},{state},{postalCode},{country}&apikey={ApiKey}");
What am I missing ?
I am getting the key from the following section
UPDATE: this problem has vanished today. It appears to have been a bug on the Here side.
Yesterday: My JS API code, which has been working fine, is throwing 401s today as well, with no changes. I could kill the project and create a new one with a new API key, but I'm not sure that would fix it. I did find that it was "disabled" (due to a billing issue, I think), and I "enabled" it and it still throws 404s.
Did you confirm your email address (by clicking the link in the email they send)?
If you have not confirmed your email address, then the API Key is only valid for 30 minutes.

Not found exception when executing request in service account

I get the following error when retrieving the events of my calendar using service account.
Can anyone tell me what I'm doing wrong.
Google.Apis.Requests.RequestError Not Found [404]Errors [Message[Not Found] Location[ - ] Reason[notFound] Domain[global]]
//file path
string GoogleOAuth2CertificatePath = Server.MapPath("GoogleStore\My Project-a725fb0190fc.p12");
// #developer... e-mail address.
string GoogleOAuth2EmailAddress = "939544675132-compute#developer.gserviceaccount.com";
// certificate password ("notasecret").
string GoogleOAuth2PrivateKey = "notasecret";
X509Certificate2 certificate = new X509Certificate2(GoogleOAuth2CertificatePath, GoogleOAuth2PrivateKey, X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(GoogleOAuth2EmailAddress)
{
Scopes = new[] { CalendarService.Scope.Calendar }
}.FromCertificate(certificate));
// Create the service.
service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName
});
ListRequest request = service.Events.List(calID);
request.ShowDeleted = false;
request.SingleEvents = true;
events = request.Execute();
Thank you for any answer what can help me.
Usually when encountering 404: Not found the specified resource was not found. This can happen in several cases.
when the requested resource has never existed.
when accessing a calendar that the user can not access.
Based on the Official Google Documentation, the suggested action is to implement exponential backoff.
Exponential backoff is a standard error handling strategy for network applications in which the client periodically retries a failed request over an increasing amount of time. If a high volume of requests or heavy network traffic causes the server to return errors, exponential backoff may be a good strategy for handling those errors. Conversely, it is not a relevant strategy for dealing with errors unrelated to rate-limiting, network volume or response times, such as invalid authorization credentials or file not found errors.
Used properly, exponential backoff increases the efficiency of bandwidth usage, reduces the number of requests required to get a successful response, and maximizes the throughput of requests in concurrent environments.
Take note that in every request, your application sends to the Google Calendar API must include an authorization token. The token also identifies your application to Google.
Here's a related SO ticket encountered 404 not found error: Error 404 when creating a calendar with Google Calendar Api v3 using c# .net

Handling authentification to Firebase Database with Fetch in a Service Worker

I'm trying to query a Firebase database from a Service Worker using the Fetch API. However it doesn't work as expected as I can't get authenticated correctly.
Basically what I'm trying to do is from origin https://myproject.firebaseapp.com inside a Service Worker I do a call like this :
var fetchOptions = {};
fetchOptions.credentials = 'include';
var url = options.messageUrl;
var request = new Request('https://myproject.firebaseio.com/user/foobar.json', fetchOptions);
messagePromise = fetch(request).then(function(response) {
return response.json();
});
I'm getting this error :
Fetch API cannot load https://myproject.firebaseio.com/user/foobar.json. Response to preflight request doesn't pass access control check: Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'https://myproject.firebaseapp.com' is therefore not allowed access.
Any idea of a way to fix it? How one should do to query/update the Firebase database from a SW?
I've read https://jakearchibald.com/2014/using-serviceworker-today/ and one of the gotcha was exactly that problem, the fact that Fetch request do not send authentification.
Ideally it would be great to be able to use the Firebase JS API inside a SW but this doesn't seem to work as well.
Firebase doesn't store authentication info as a cookie or in anything that would be sent along in the credentials, so there's no need to send them in your fetch request. Instead, you'll need to pull the token from Firebase Auth:
firebase.auth().currentUser.getToken(true).then(function(token) {
// token is the value you'll need to remember for later
});
Once you've got the token, you should be able to add it as a query parameter to the REST request e.g. ?auth={THE_TOKEN}. This will allow you to make your authenticated request in the Service Worker.

Get token from ADFS

I'm trying to obtain a token from ADFS to that I can use it with an on-premise Windows Service Bus installation. I may not have ADFS properly configured because I get the following message:
MSIS3127: The specified request failed.
The code to access the token is as follows:
string adrecaSTS = "trust/13/usernamemixed";
WS2007HttpBinding binding = new WS2007HttpBinding();
binding.Security.Message.EstablishSecurityContext = false;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
binding.Security.Mode = SecurityMode.TransportWithMessageCredential; //https
string baseSSLUri = #"https://<myadfs>/adfs/services/";
WSTrustChannelFactory trustChannelFactory = new WSTrustChannelFactory(binding, new EndpointAddress(baseSSLUri + adrecaSTS));
trustChannelFactory.TrustVersion = TrustVersion.WSTrust13;
trustChannelFactory.Credentials.UserName.UserName = "username";
trustChannelFactory.Credentials.UserName.Password = "password";
WSTrustChannel tokenClient = (WSTrustChannel)trustChannelFactory.CreateChannel();
//create a token issuance issuance
RequestSecurityToken rst = new RequestSecurityToken(RequestTypes.Issue);
//call ADFS STS
SecurityToken token = tokenClient.Issue(rst);
The endpoint is enabled on ADFS and my client (laptop on separate domain) trusts the certificate from ADFS.
Do I need to set up some kind of trust or something further? This error message is not particularly helpful.
See here:
https://github.com/thinktecture/Thinktecture.IdentityServer.v2/blob/master/src/Libraries/Thinktecture.IdentityServer.Protocols/WSFederation/HrdController.cs
The ValidateToken method has most of the code - but you first need to extract the InnerXml from the generic token and turn that into a SAML security token (again using a token handler).
Found the issue. I was trying to log on as an administrator account. When I used a regular user it worked.
I also had to modify the RequestSecurityToken to have a KeyType of KeyType.Symmetric
I see that you solved your issue, but here is some additional inforamation to potentially help others that might have the same error message but a different cause.
The AD FS error, "MSIS3127...", can have multiple causes. For us, it was caused by one of our relying party claim rules specifying an AD FS attribute store that didn't exist.
In order to debug the error, we checked the Event Viewer on all of the servers running AD FS, and that's where we found the detailed message that called out the attribute store problem. So, if anyone else gets the same error message, then I suggest checking the Event Viewer on AD FS to see if there are additional logs.
Note that AD FS logs to the Event Viewer under the folder/node of Applications and Services Logs => AD FS => Admin

The Access Token is Valid but We get OAuthException: An active access token error

We've been working on an application for about 2 months, and everything was going perfectly.
we were using PHP SDK and offline mode in permissions for login
But since some days ago after recent changes in Facebook api and removing offline mode we started facing the problem of "Uncaught OAuthException: An active access token must be used to query information about the current user."
The main problem is that it does happen after a while working in our app (about 10 mins) but at the same time when we check the validity of the token via this link
we see that the token is still valid on the other hand the cookie does still exist and it doesn't expire but we get this error :
"Uncaught OAuthException: An active access token must be used to query information about the current user"
I've already visited this link
and I downloaded the latest version but it didn't help could anyone help us please where might be making mistake?
Thanks for responses, I think same as yacon
it seems there's a bug when accessing facebook->api(/me) at the moment we are handling
some parts of the app with javascript which is a real headache to use javascript sdk
and PhP sdk alongside with each other
You can solve this simply store accesstoken to session variable after getLoginUrl
$facebook->getLoginUrl(...)
then whenever you initialize facebook
$facebook = new Facebook(array(
'appId' => Yii::app()->params['facebook_appId'],
'secret' => Yii::app()->params['facebook_appSecret'],
));
get the accesstoken from session and set it using setAccessToken
$facebook->setAccessToken(Yii::app()->session['access_token']);
I handle this situation in this way
1.i get the access token for 1 hour validity
2.extend the token to 60 days validity
3.save that token to session and use it for all project queries.
try{
$facebook_uid = $facebook->getUser();
$facebook->setExtendedAccessToken();
$accessToken = $facebook->getAccessToken();
$fbuser = $facebook->api('/me');
$session['api_me'] = $fbuser;
$session['tokenValue'] = $accessToken;
}catch (Exception $e) {
facebook_uid =null;
}
I think there is a bug in the api. When I use $facebook->api('/'.$facebook_uid) instead of ->api('/me') it works.

Resources