Showing posts with label oAuth 2.0. Show all posts
Showing posts with label oAuth 2.0. Show all posts

Thursday, November 3, 2016

Not receiving Google OAuth refresh token

The refresh_token is only provided on the first authorization from the user. Subsequent authorizations, such as the kind you make while testing an OAuth2 integration, will not return the refresh_token again.

Go to your account security settings: 
https://security.google.com/settings/security/permissions?pli=1.

Then click "Revoke Access" next to your app.
The next OAuth2 request you make will return a refresh_token.

You need "access_type=offline" & "approval_prompt=force" in all cases when you want the refresh_token.

Using OAuth 2.0 for Google Client-side Web Applications


http://pritomkumar.blogspot.com/2016/11/php-send-email-using-google-oauth2.html
1. Obtain OAuth 2.0 credentials from the Google API Console.
First visit to https://console.developers.google.com/ and follow the steps:
Click the "Credentials" as below image:


Now click on "Create credentials" right most part of button and then you can see a dropdown menu as below image:


Now click on "OAuth client ID"
It will show a page like and select "Web application" as below image and provide "Name" and "Authorized redirect URIs" as described and click "Create":



NB: it can say you to create a project, then create a project by click the button.

It will take you to the OAuth client page where you can see "Client ID" & "Client Secret" which would be need later.




You can enable any of your service from google account from list below for specific project:




All google products listed here:
https://developers.google.com/products/

2. Now its time to connect to google via OAuth (Its PHP code snippet):
You have to define your scope first:
$scope = "https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/gmail.readonly";
$auth_url = "https://accounts.google.com/o/oauth2/v2/auth";
$client_id = "YOUR CLIENT ID FROM GOOGLE";
$redirect_uri = "http://localhost/tappi/";

$forward_url = $auth_url."?scope=".$scope."&redirect_uri=".urlencode($redirect_uri)."&response_type=code&client_id=".urlencode($client_id);
header("Location: ".$url);

It will redirect you to the following page (if not logged in, login then):




Now click "Allow" button direct you to url you provided when creating application with a code in get parameter
Now you can get access token using the code received.
Full example code below:


<?php
session_start();
init();

if(token() != null) {
    echo "<a href='".$_SESSION["redirect_uri"]."'>Home</a>";
    echo " || <a href='".$_SESSION["redirect_uri"]."?refresh_token=true'>Refresh token</a>";
    echo " || <a href='".$_SESSION["redirect_uri"]."?profile=true'>Profile</a>";
    echo " || <a href='".$_SESSION["redirect_uri"]."?logout=true'>Logout</a><br/><br/>\n\n";
}

if(isset($_GET["logout"])) {
    flushToken();
    echo "Logged out<br/>";
    echo "<a href='".$_SESSION["redirect_uri"]."'>Start new session</a>";
    die();
}
else if(isset($_GET["refresh_token"])) {
    refreshToken();
    header("Location: ".$_SESSION["redirect_uri"]);
}
else if(isset($_GET["profile"])) {
    viewProfile();
}
else if(token() != null) {
    echo "<pre>";print_r(token());echo "</pre>";
}
else if(isset($_GET["code"])) {
    $post = "code=".urlencode($_GET["code"])."&client_id=".urlencode($_SESSION["client_id"]);
    $post .= "&client_secret=".urlencode($_SESSION["client_secret"]);
    $post .="&redirect_uri=".urlencode($_SESSION["redirect_uri"]);
    $post .= "&grant_type=authorization_code";
    $result = json_decode(runCurl($_SESSION["token_url"], $post));
    storeToken($result);
    if(isset($result->refresh_token)) {
        file_put_contents("rt-".getUserID().".txt", $result->refresh_token);
    }
    file_put_contents("active.txt", getUserID());
    file_put_contents("access_token.txt", $result->access_token);
    header("Location: " . $_SESSION["redirect_uri"]);
}
else {
    $url = $_SESSION["auth_url"]."?scope=".urlencode($_SESSION["scope"]).
        "&redirect_uri=".urlencode($_SESSION["redirect_uri"]).
        "&response_type=code&client_id=".urlencode($_SESSION["client_id"])."&access_type=offline";
    echo "<a href='".$url."'>Authorize with Google</a>";
}

function refreshToken() {
    $post = "client_id=".urlencode($_SESSION["client_id"]);
    $post .= "&client_secret=".urlencode($_SESSION["client_secret"]);
    $post .= "&redirect_uri=".urlencode($_SESSION["redirect_uri"]);
    $post .= "&grant_type=refresh_token&refresh_token=".urlencode(getRefreshToken());
    $result = json_decode(runCurl($_SESSION["token_url"], $post));
    file_put_contents("access_token.txt", $result->access_token);
    storeToken($result);
}

function getRefreshToken() {
    $active = file_get_contents("active.txt");
    return file_get_contents("rt-".$active.".txt");
}

function flushToken() {
    file_put_contents("auth.txt", "");
    $_SESSION["redirected"] = null;
}

function token() {
    $text = file_exists("auth.txt") ? file_get_contents("auth.txt") : null;
    if($text != null && strlen($text) > 0) {
        return json_decode($text);
    }
    return null;
}

function storeToken($o) {
    file_put_contents("auth.txt", json_encode($o));
}

function init() {
    $_SESSION["auth_url"] = "https://accounts.google.com/o/oauth2/v2/auth";
    $_SESSION["token_url"] = "https://accounts.google.com/o/oauth2/token";
    $_SESSION["client_id"] = "892386593019-xxxxxxxxxinht701m7kn0gkoj964r2.apps.googleusercontent.com";
    $_SESSION["client_secret"] = "bVQ_xT0ZxxxxxxxxxxvV9zRV3";
    $_SESSION["redirect_uri"] = "http://localhost/tappi/google.php";
    $_SESSION["scope"] = "https://www.googleapis.com/auth/userinfo.profile"; /* User profile */
    $_SESSION["scope"] .= " https://www.googleapis.com/auth/userinfo.email"; /* User email address */
    $_SESSION["scope"] .= " https://www.googleapis.com/auth/gmail.readonly"; /* Read mail */
    $_SESSION["scope"] .= " https://www.googleapis.com/auth/gmail.send"; /* Send email */
}

function getUserID() {
    $fromSession = valueFromSession("google_user_id");
    if($fromSession) {
        return $fromSession;
    }
    else {
        $apiUrl = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json";
        $apiUrl .= "&access_token=".token()->access_token;
        $result = json_decode(runCurl($apiUrl));
        $_SESSION["google_user_id"] = $result->id;
        return $_SESSION["google_user_id"];
    }
}

function valueFromSession($name) {
    if(isset($_SESSION[$name])) {
        return $_SESSION[$name];
    }
    return null;
}

function viewProfile() {
    $apiUrl = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json";
    $apiUrl .= "&access_token=".token()->access_token;
    $result = json_decode(runCurl($apiUrl));
    echo "<pre>";
    print_r($result);
    echo "</pre>";
}

function runCurl($url, $post = null, $headers = null) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, $post == null ? 0 : 1);
    if($post != null) {
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
    }
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSLVERSION, 1);
    if($headers != null) {
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    if($http_code >= 400) {
        echo "Error executing request to Office365 api with error code=$http_code<br/><br/>\n\n";
        echo "<pre>"; print_r($response); echo "</pre>";
        die();
    }
    return $response;
}
?>



Sunday, April 7, 2013

Google APIs Console and service account setup

Google php library

https://code.google.com/p/google-api-php-client/wiki/OAuth2

https://docs.google.com/file/d/0B5nZNPW48dpFMTA5OU1SbUNkMW8/edit?usp=sharing

Overview

OAuth 2.0 is an emerging standard for accessing protected resources on the web. The Google APIs and the google-api-php-client library support OAuth 2.0.

Further Reading

Overview

Use OAuth 2.0 to access to protected data through the Google APIs. Google APIs support a variety of flows designed to support different types of client applications. With all of these flows the client application requests an access token that is associated with only your client application and the owner of the protected data being accessed. The access token is also associated with a limited scope that define the kind of data the your client application has access to (for example "Manage your tasks"). An important goal for OAuth 2.0 is to provide secure and convenient access to the protected data, while minimizing the potential impact if an access token is stolen.

Google APIs Console

Before you can use OAuth 2.0, you must register your application using the Google APIs Console.
Visit the Google API Console to generate your developer key, OAuth2 client id, OAuth2 client secret, and register your OAuth2 redirect uri. Copy their values since your will need to input them in your application.
  • From the "Services" screen, activate access to the API you want to use.
  • Click on "API Access" in the left column
  • Click the button labeled "Create an OAuth2 client ID"
  • Give your application a name and click "Next"
  • Select your "Application type"
  • Click "Create client ID"
  • Click "Edit..." for your new client ID
  • Under the callback URL, enter the fully qualified URL for your PHP application (example http://localhost/googleplus/index.php).

Web Application

Now that you've registered your application with the Google APIs Console, you can now create a web application that uses OAuth 2.0. Here is an example demonstrating how to do authentication with OAuth 2.0 in a web application. The full code for this sample is in the repository.
<?php
require_once 'path/to/Google_Client.php';

$client = new Google_Client();
$client->setClientId('insert_your_oauth2_client_id');
$client->setClientSecret('insert_your_oauth2_client_secret');
$client->setRedirectUri('insert_your_oauth2_redirect_uri');
$client->setDeveloperKey('insert_your_developer_key');
If the user has been redirected back to our page with an authorization code, exchange the code for an access token.
if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

Service Accounts

Service Accounts provide certificate-based authentication for server-to-server interactions. This means, for example, that a request from a web application to Google Cloud Storage can be authenticated via a certificate instead of a shared key. Certificates offer better security properties than shared keys and passwords, largely because they are not human-readable or guessable.
Warning: Very few Google APIs currently support Service Accounts. Service accounts are currently supported by the following Google developer services:
  • Google Cloud Storage
  • Google Prediction API
  • Google URL Shortener
  • Google OAuth 2.0 Authorization Server
  • Google BigQuery
To get started:
  1. Visit https://code.google.com/apis/console
  2. Press the down arrow in the left panel (under the Google apis logo).
  3. Press create.
  4. Name your project "Prediction Test Project".
  5. Press create project.
  6. Now a list of APIs should appear. You want to find "Prediction API" and switch that API to "ON".
  7. Select the API Access tab on the left side.
  8. Press "Create OAuth 2.0 Client" and create your client.
  9. Select Service Account as the application type.
  10. Press Download private key.
Now open the examples /prediction/serviceAccount.php sample application in your editor.
  • Make sure you have a recent version of the Google APIs PHP Client downloaded from here.
  • Replace CLIENT_ID with your newly generated clientId. It should look like:
  • xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com
  • Replace SERVICE_ACCOUNT_NAME with the email address. It should look like:
  • xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com
  • Replace KEY_FILE with the path to your private key. Make sure it is saved in a safe place, and readable the sample app.
// Set your client id, service account name, and the path to your private key.
// For more information about obtaining these keys, visit:
// https://developers.google.com/console/help/#service_accounts
const CLIENT_ID = 'insert_your_client_id';
const SERVICE_ACCOUNT_NAME = 'insert_your_service_account_name';
// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
const KEY_FILE = '/super/secret/path/to/key.p12';
// Load the key in PKCS 12 format (you need to download this from the
// Google API Console when the service account was created.
$client = new Google_Client();
...
$key = file_get_contents(KEY_FILE);
$client->setClientId(CLIENT_ID);
$client->setAssertionCredentials(new Google_AssertionCredentials(
  SERVICE_ACCOUNT_NAME,
  array('https://www.googleapis.com/auth/prediction'),
  $key)
);
There is a full sample of using the Prediction API with a Service account.
Learn more about Service accounts from the announcement.


Solving invalid_grant errors

Make sure your server's clock is in sync with NTP.


Here is the URL:
The value which you are referencing is:  54774085
And this is also the value I see in the admin area for "Profile ID"  (54774085)

I had used Service Account for Google Analytics, and get token and get data from google analytics in ruby. It's work for me.
You can try to setup Google Analytics to work with your newly created Service Account:
        -Open Admin section of Google Analytics
        -Click on Users and create a new user in Analytics with the e-mail address provided by the Google API Service Account I had done state above. and i resolve error 403.