google analytics custom plugin getting error invalid grant - google-analytics

$client = new Google_Client();
$client->setAuthConfigFile(plugin_dir_url( __FILE__ ) . '/client_secrets.json');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->setIncludeGrantedScopes(true);
$client->setAccessType('offline');
$client->revokeToken();
$auth_url = $client->createAuthUrl();
using a popup authentication with javascript and then
if (!isset($_SESSION['access_token'])) {
//$client->authenticate($_GET['code']);
if($client->isAccessTokenExpired()){
$client->authenticate($this->options['authenication_code']);
$refreshToken = $client->getRefreshToken();
$client->refreshToken( $refreshToken );
$accessToken = $client->getAccessToken();
}
$_SESSION['access_token'] = $accessToken ? $accessToken : $refreshToken;
}
After authenticating It is giving the result ,but while using another session to get the data it is showing errors different error in different circumstances no clear idea
Google_Auth_Exception' with message 'Error fetching OAuth2 access
token, message: 'invalid_grant: Invalid code.'
Google_Auth_Exception' with message 'Error fetching OAuth2 access
token, message: 'invalid_grant' if checked after some time
Google_Auth_Exception' with message 'Error fetching OAuth2 access
token, message: 'invalid_grant: Code was already redeemed.' authenticated closed the browser and try with another browser
This is my 4th week on this but still unable to get things correctly.
I have gone through certain posts but no luck
1.Unable to refresh OAuth2 token in PHP, invalid grant
2.authenticate() accepts invalid tokens
3.Getting "invalid_grant" error on token refresh
4.Problem in refreshing access token
5.Why do I keep catching a Google_Auth_Exception for invalid_grant?
6.How to refresh token with Google API client?
7.Google OAuth2 - access token & refresh token -> invalid_grant/Code was already redeemed
8.Use OAuth Refresh Token to Obtain New Access Token - Google API
9.Using refresh_token for Google OAuth 2.0 returns http 400 bad request
and some more if I need to post more codes or anything else please let me know.
full code

Related

Firebase authentication facebook provider usage with signInAndRetrieveDataWithCredential()

I'm trying to set up facebook sign-in to my react-native app using firebase. I am successfully authenticating with facebook using the integrated facebook support with expo and am getting a facebook-token. Unfortunately however, I'm having issues using this token to sign-in with firebase getting a "Invalid IdP response/credential" error.
I have used the exact same flow (but using Google Provider and token) for google login and been successful. I have also been able to use the facebook token to get data from facebook's rest API showing validity of token.
//This function gives the error
doSignInWithFacebookCredential = (facebookToken) => {
const credential = this.facebookProvider.credential(facebookToken);
this.auth.signInAndRetrieveDataWithCredential(credential)
.then(authUser => {
alert("It worked!")
})
.catch(function(error) {
alert(error)
});
}
//Code used to verify facebook token
const response = await fetch(`https://graph.facebook.com/me?access_token=${facebookToken}`);
console.log(await response.json())
//This function works perfectly (The google sign-in with same flow)
doSignInWithGoogleCredential = (googleToken) => {
const credential = this.googleProvider.credential(googleToken);
console.log(credential)
this.auth.signInAndRetrieveDataWithCredential(credential)
.then(authUser => {
alert("It worked!")
})
.catch(function(error) {
alert(error)
});
}
After receiving the valid facebook token an error occurs resulting in an alert from the catch that says
Error: Invalid IdP response/credential: http://localhost?id_token=$facebookToken&providerId=facebook.com
TLDR; Despite having a valid facebook token it seems facebookProvider.credential(facebookToken) is not giving a valid token to the signInAndRetrieveDataWithCredential() function causing a 'Invalid IdP response/credential' error.
If anyone has worked with these methods before or has any suggestions they are all greatly appreciated.
Thrown if the credential is malformed or has expired, and for that reason it returns invalid idp response credentials.
Since This method is deprecated, i suggest to use firebase.auth.Auth.signInWithCredential instead. And, maybe in this way, you will get more details if there is a problem with credential or not
Hope this helps!

Is email authentication using id token possible?

I'm creating a POC for an iOS application that uses extension. The extension has to know if a user is authenticated. Unfortunately a containing app and an extension are separate application which means I have to keep auth state somewhere.
I don't want to store user email and password but instead a token and use it to authenticate. However trying to authenticate with the issued token and providerId (Firebase) does seems to work.
Both apps under the same Firebase project.
Main Application (Firebase ios App1):
let userDefatuls = UserDefaults(suiteName: "group.test")
userDefatuls?.set(providerId!, forKey: "providerId")
userDefatuls?.set(value!, forKey: "token")
print("Saved value to user defaults \(value!)")
userDefatuls?.synchronize()
Extension Application (Firebase ios App2):
let userDefaults = UserDefaults(suiteName: "group.test")
let token = userDefaults?.string(forKey: "token")
let providerId = userDefaults?.string(forKey: "providerId")
print("What is the provider id \(providerId)")
let credential = OAuthProvider.credential(withProviderID: providerId!, accessToken: token!)
Auth.auth().signIn(with: credential) { (user, error) in
print("********* What is the user \(user) what is the error \(error)")
}
The above renders:
What is the user nil what is the error:
Optional(Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information., NSUnderlyingError=0x600000447290 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 400;
errors = (
{
domain = global;
message = "INVALID_PROVIDER_ID : Provider Id is not supported.";
reason = invalid;
}
);
message = "INVALID_PROVIDER_ID : Provider Id is not supported.";
}}}})
Do you know if the support and works? Is there something what I'm doing wrong?
You can't sign in with a Firebase ID token. What you can do is:
Create an endpoint that takes an ID token, verifies it:
https://firebase.google.com/docs/auth/admin/verify-id-tokens
and returns a custom token:
https://firebase.google.com/docs/auth/admin/create-custom-tokens
You then signInWithCustomToken in the extension.
However, this could open a vulnerability as if a short lived ID token is leaked, the attacker can exchange it for a permanent session via that endpoint.
You can only return the custom token if the auth_time on the ID token is recent. This ensure that a recently signed in user can sync their app to with the extension.

web api 2 owin bearer token JwtFormat , how to return the same token for several logins (OAuthAuthorizationServerProvider and external)

I have an authentication server that return a token for several platforms (mobile,web etc),
then with this token they can do requests to my API .
Something like this : http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/
Now i need to add external login (facebook ,google,twitter).
I implemented it like in this guide :
http://www.asp.net/web-api/overview/security/external-authentication-services
What that i don't understand is how can i return the same token like i return in the regular authentication (for be able to request the API later) .
My api know only the custom jwt token .
Do i need to do it manually from GetExternalLogin function ?
If yes so i did something like this :
var ticket = new AuthenticationTicket(identity, props);
var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
And now i need to know
1)need to add to properties IssuedUtc ,ExpiresUtc , how ? in the regular authentication is automatic filled
2)How to return it to client ?
I saw that in account controller in the end i need to do :
Authentication.SignIn(identity);
And in provider :
context.Validated(ticket);
maybe i can do the same in account controller ?
Thanks.

How to get user access token using LinkedIn Javascript API like in Facebook?

I am developing a native Mobile App and what i need is to pass a users's access token and get user details for doing mobile based operations. I was able to achieve the same in Facebook. But how can i get the access token of user via LinkedIn JavaScript API.
Facebook API way:
function statusChangeCallback(response) {
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
console.log(response); ===> GOT USER ACCESS TOKEN FROM THIS RESPONSE
testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
Any help to get the same in LinkedIn will be very much appreciated.
Check out the LinkedIn's Documentation on Exchanging JSAPI tokens for OAuth tokens.

Getting Google Oauth2 Token using dotnetopenauth

I'm having an issue retreiving the OAuth2 token for google using DotNetOpenAuth 4.2.0.13024.
I've got to the point where I can successfully make the authorization request to the google endpoint https://accounts.google.com/o/oauth2/auth
When the user clicks 'OK', google then calls my callback URL as expected with the appropriate "code" query string.
However, I am unable to exchange this code for a token, as my calls keep failing with "Protocol exception was unhandled" execption and "400 Bad request" as the inner exception. This is the code I am using to exchange the token
private static AuthorizationServerDescription authServerDescription = new AuthorizationServerDescription
{
TokenEndpoint = new Uri("https://accounts.google.com/o/oauth2/token"),
AuthorizationEndpoint = new Uri("https://accounts.google.com/o/oauth2/auth")
};
static GoogleContacts()
{
Client = new WebServerClient(authServerDescription, "{my_cliend_id}", "{me_secret_key}");
}
var authorization = Client.ProcessUserAuthorization(); // <- Exception is thrown here
if (authorization != null)
{
Authorization = authorization;
Response.Redirect(Request.Path); // get rid of the /?code= parameter
}
PS: it seems like a new version of DotNerOpenAuth has been released but, I am unable to get it because the zip download still points to the older version and Nuget keeps failing on me :(

Resources