I started a project using the Google API signin mixed with an angularJS+Firebase app.
What I would like to do is to be able to send an e-mail from one person to another programmatically.
Example: John is logged in, clicks on a button which sends an email to Rachel. But that email is sent using the stored token from Ted, not John's account.
It seems possible using the php library which is not an option here.
So far, I get the token easily using these few lines:
var GoogleAuth = gapi.auth2.getAuthInstance();
GoogleAuth.grantOfflineAccess({
scope: 'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/drive https://mail.google.com/ profile email'
}).then(function(resp) {
console.log(resp);
this.storeToken(resp.code);
});
Is it actually possible ?
A quick search just got me results for php or about how you get a token with the JS library... not how to use it !
From my understanding you want to use a refresh token ( offline access ) to send an email from Ted's account via Javascript.
Sadly this is not possible client side. What your code gives you is a 'code' that you can send to your server using a $http.post () and trade with Google server side for a refresh token.
Here is a guide for how to change that code into a refresh token.
While you can do this client side it would involve exposing your client secret which you should never do.(https://developers.google.com/identity/sign-in/web/server-side-flow)
Every time John wants to send an email from Ted's account your application will have to send a request to your server that:
Sends a request to google with the refresh token and generates an access token (https://developers.google.com/identity/protocols/OAuth2WebServer#offline)
Sends a seccond request to google using the access token to send the email from Ted's account
I hope that this helped.
Related
I'm developing an app with Ionic 3 and Angular 4, and also implementing Login With Facebook button (and logic).
I don't understand how to secure this process.
The API returns the user's email + id and then I need to send them to my server to register / log in the user.
But how can I be sure that nobody "fake" the ajax call with those user email & id? And skip the whole Facebook Button process?
I don't get it at all - no matter what the API returns - I need to send it to the server via AJAX, and anyone can fake this process and send specific parameters with AJAX.
A good way is to send the Access Token to the server and make the API call to the Facebook API there. You can/should activate "Require App Secret" in the App settings:
Only allow calls from a server and require app secret or app secret
proof for all API calls.
The answer is - backend!
You should always verify the token in the server side to prevent "hacks" like you said
My project has the requirement to access the yammer data using the given REST API using server side script(mainly PHP) and not involve a client side login using yammer's OAuth dialog.
I have gone through this document:
https://developer.yammer.com/docs/oauth-2
but this says, we requires user interaction.
What I wanted was can I generate a client_id and client_Secret to further generate access token to make API call out, but in all these processes I only use the authenticated users username and password in my server-side script.
Can anyone suggest a solution or is a client-side interaction required by design?
Thanks in advance!!
You have to have a user authorize the application at least once. This is just the nature of the OAuth implementation and you can't work around it. Having users go through the OAuth flow is considered a best practice.
If you have an OAuth token for a verified admin of Yammer, you can use impersonation to get tokens for end users without them interacting with the OAuth flow.
The below from Microsoft blogs might help you & added source at the end of answer.
Obtain a Verified Admin token for your application in one of the following 2 ways
a. Create the app with a Verified Admin account and then in the app’s Basic Info page, click “Generate a developer token for this application.” Note that you’ll need to use this app’s info in the JS SDK and any subsequent calls.
b. Use the process outlined at https://developer.yammer.com/docs/test-token with a Verified Admin account to get an OAuth token for that VA account. Note that you must use the app info used to generate this token in all future steps.
Obtain the current user’s email address in the server-side script.
Using the VA token obtained in step 1 to authenticate, pass the user’s email address to our Get User by Email Address endpoint documented at https://developer.yammer.com/docs/usersby_emailjsonemailuserdomaincom, and then process the response
a. If the call to the API endpoint returns a 200 OK response, first check the “state” field to make sure the user is “active” and if so, store the “id” field that’s returned and go to step 4
b. If the call returns a 404 or a state other than “active,” direct the user to finish creating and activating their account however you like.
Once you have the user’s ID, you can pass it to our Impersonation endpoint to obtain a pre-authorized OAuth token for that user. This endpoint is documented at https://developer.yammer.com/docs/impersonation and must use the VA token obtained in step 1 to authorize the call, and the consumer_key of your JS SDK app.
You now have an OAuth token for the current user. When generating the code being passed to the browser, have the client side JS SDK code first call yam.platform.getLoginStatus and if there’s no active session and you have a token from step 4, pass that token to yam.platform.setAuthToken($tokenFromStep4, optional_callback_function_if_desired(response)). If you don’t have a valid token, direct the user to finish setting up their Yammer account.
Continue making JS SDK calls as you normally would, without needing the user to authenticate.
Source: https://blogs.technet.microsoft.com/askyammer/2016/11/04/preauthorizing-the-yammer-js-sdk/
What I am doing:
I am integrating Google Picker on my page. This will allow users to select files from their Google Drive to be used in the web app. In the app, people in a group share a common google drive (i.e. they all can select files from account example#email.com) which was created by group admin by his email address. When the admin signs-up for the account we do OAuth and get access_token with refresh_token against our app on google (with offline access enabled). I plan to use the access_token and refresh-token of the admin, on other group user's account when they try to use picker to select files.
What I have done:
I have integrated the Google Picker successfully in my app using the basic code provided in docs. Then to achieve what I wanted, I removed following code from the example code:
gapi.load('auth', {'callback': onAuthApiLoad});
and
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
}
and
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
and instead of .setOAuthToken(oauthToken) I pass refreshed access_token directly as string (I get that from my server with an ajax call).
.setOAuthToken("<access_token>")
But every time I call picker.setVisible(true); I get a screen in an iframe saying In order to select an item from your online storage, please sign in.
Problem:
Try to add sign in listener. Listeners provide a way to automatically respond to changes in the current user's Sign-In session. For example, after your startup method initializes the Google Sign-In auth2 object, you can set up listeners to respond to events like auth2.isSignedIn state changes, or changes in auth2.currentUser.
Validating the token might be a possibility before using the token each time but that might add a lot of extra overhead for a rare use-case each time we load the picker and when calling the API endpoints with a token after the re-authentication issue, there was no key about the token being invalid. You can validate a token by making a web service request to an endpoint on the Google Authorization Server and performing a string match on the results of that web service request.
I'm working on a intranet-based application and I want to use Google services. Currently I have successfully implemented Google Authentication with "Sign-In for Websites" using JavaScript client-side authentication. My users can now sign in or sign up with their Google accounts.
Now I want to use Google API to create and share Google Sheets with my users. These documents will be created with a specific Google account and then shared with my users.
This is why I want to use this server-slide flow to get a one-time authorization code and exchange it for a refresh token:
https://developers.google.com/identity/sign-in/web/server-side-flow
This refresh token will be stored in my database allowing me to user Google services on behalf of this offline user.
Using JavaScript library, I was able to get the one-time authorization code that I send to my server with a AJAX request.
auth2.grantOfflineAccess({'redirect_uri': 'postmessage'}).then(grantOfflineAccessCallback);
var grantOfflineAccessCallback = function(authResult) {
var auth_code = authResult.code;
// Exchange the one-time authorization code for tokens
$.post(...);
}
On server-side I use Google API PHP Client (v2.0.0-RC6) to acquire an access and refresh token.
$this->client = new Google_Client();
$this->client->setClientId($this->clientId);
$this->client->setClientSecret($this->clientSecret);
$this->client->setAccessType('offline');
$this->client->setApprovalPrompt('force');
$response = $this->client->fetchAccessTokenWithAuthCode($oneTimeCode);
I wasn't able to exchange the authorization code.
Client error: `POST https://www.googleapis.com/oauth2/v4/token` resulted in a `400 Bad Request` response:
{
"error": "invalid_request",
"error_description": "Missing parameter: redirect_uri"
}
On this page we can read:
On the server, exchange the auth code for access and refresh tokens.
Use the access token to call Google APIs on behalf of the user.
On the JAVA example code:
REDIRECT_URI: // Specify the same redirect URI that you use with your web
// app. If you don't have a web version of your app, you can
// specify an empty string.
Because the application I working on is an intranet application, I tried to specify an empty string for this redirect_uri parameter before calling fetchAccessTokenWithAuthCode() method:
$this->client->setRedirectUri('');
... result in Redirect URI must be absolute.
Can we use this hybrid server-slide flow without callback URL?
Is there any solution to my problem?
Thanks,
Edit:
redirect_uri is where the user will be redirected to after he signed in. This URL must be registered in the Google Project (developers console). So redirect_uri is NOT the callback...!
Problem is now solved with:
$this->client->setRedirectUri('http://same.url.as.in.developers.console/');
I am making an ajax controlled website, in which I use the Javascript SDK for Google to authenticate my users, and gain access to their google contacts. What I intend to do, is the following:
Authenticate the user in the browser, withour redirecting and ask for access to their Contact list, and access to manage their Contacts.
Store the user id in my database if he/she granted me the access, together with a refresh token, which if I am not mistaking, I can only get via server side.
Sometime later, if the user wants to see their google contacts via my website, send an ajax request to my server, which ASKS for an access_token from the user, retrieves the data and shows it to the user, or stores it in my own database if the user asks to.
I've managed to complete the first step from these three, I can authenticate a user, and get access to a single access token which is valid for 3600 hours, but I can't figure out how to authenticate a user server side, without redirecting him anywhere. I tried using the Google PHP SDK too, but can't seem to figure out how to do this. I am certain that this is possible somehow, because it is stated in the Google PHP SDK guide:
If we have authenticated on an Android or Javascript web client, we may have aquired a code via a different means. In this case, we just need to exchange it. If it was retrieved via the gapi Javascript client, we need to set the redirect URI postmessage.
$client->setRedirectUri($redirect_uri);
The only problem is I don't understand how to do this. What is $redirect_uri? I don't have a redirect url, becase when I implemented the Javascript SDK, there it said, that I don't have to use a redirect uri, because Javascript authentification is done in the same window, without redirects(just as I want it).
How could I proceed to solve the second and the third step mentioned above? Where could I find a non-hacky or not-very-much-hacky tutorial, to achieve my desired result?
EDIT:
What I basically want to achieve is the following things:
ask for permission to access Google Contacts from the user, WITHOUT redirecting him from my site(via a popup window)
Achieved this with the Javascript SDK
get an access token for this permission, and a refresh token, and STORE these in a database
Javascript SDK only grants an access token, and I don't want to pass this via an ajax call, because I feel this is unsecure
with the refresh token, generate access tokens server side for the user, and process data, and send the data back.
Here is how my PHP file looks at the moment:
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setScopes('https://www.googleapis.com/auth/plus.me');
$client->setRedirectUri($PHP_SELF);
$client->setState('offline');
$authUrl = $client->createAuthUrl();
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$result=$client->getAccessToken();
} else {
header("Location: ".$authUrl);
exit;
}
To achieve what I want, I should get the $_GET['code'] parameter somehow through the Javascript SDK, but I don't know how:|
After a few days of headache I figured this one out too... thanks Google for nothing, your documentation SUCKS.
$client->setRedirectUri($redirect_uri);
The $redirect_uri parameter should be a string: "postmessage", and when authenticating via javascript, you should ask for a CODE instead of a TOKEN, which you then send to your server side script, to authenticate and exchange for a token.
gapi.auth.authorize({client_id: googleApi.clientId, scope: googleApi.scopes, response_type: 'code', immediate: true}, g_handleAuthResult);