I am currently using the fitbit library with a laravel wrapper (see https://github.com/popthestack/fitbitphp).
I am attempting to store the access token once a user authenticates and then subsequently reuse that token instead of having to make a separate request for a new token each time. Is it possible using fitbits oauth 1 implementation to reuse the access tokens or will I need to make a new request using request tokens etc. each time. I apologize in advance, I have a fairly visceral understanding of oauth in the first place but fitbit in particular has been tripping me up. Thanks.
here is the function I have that requests info from fitbit...
public function getFitbit() {
// get data from input
$code = Input::get( 'oauth_token' );
// get fb service
$fb = fitbitOauth::consumer( 'Fitbit' );
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from fitbit, get the token
$fb->requestAccessToken(
$_GET['oauth_token'],
$_GET['oauth_verifier']
);
// Send a request now that we have access token
$result = json_decode($fb->request('user/-/profile.json'));
print_r($result);
}
// if not ask for permission first
else {
// get fb authorization
$token = $fb->requestRequestToken();
$url = $fb->getAuthorizationUri(array('oauth_token' => $token->getRequestToken()));
// return to facebook login url
return Redirect::to( (string)$url );
}
}
I can run through the above example. Direct a user to the page where they can authenticate their account. This then redirects to a page that displays their info. If I reload the page with the 'token' and 'verifier' set already it fails. I want to be able to save off their token to a DB and reference it in the future.
Related
I am building a portal where multiple users can log in to their multiple Gmail accounts. I have successfully retrieved the token value, However, I want to store that in my database but I am unable to store it.
Below is the code I am using:
function mInititalize(){
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://mail.google.com/');
$client->setClientId(Config('gmail.client_id'));
$client->setClientSecret(Config('gmail.client_secret'));
$client->setRedirectUri('http://localhost:81'.Config('gmail.redirect_url'));
$loginURL = $client->createAuthUrl();
return redirect($loginURL);
}
After Redirection or user login
function mGetToken(){
$token = $client->fetchAccessTokenWithAuthCode( 'code'); // here i get the 'code' from login URL
I pass this code to get token I successfully get token
$oAuth = new Google_Service_Oauth2( $client);
$userData = $oAuth->userinfo_v2_me->get(); // get current user detail
}
I want to store $token value in database, but I am getting error message
>Serialization of 'Closure' is not allowed
Please anyone help me to solve this issue. Thanks.
I would suggest storing OAuth credential information for the Google API, not in your database, but through the API itself. If you're intending to use it any authentication manner, you'll run into problems, as the docs state:
Access tokens periodically expire and become invalid credentials for a related API request. Google Identity Platform: Using OAuth 2.0 for Web Server Applications
But, the same docs also show a way that you can set or retrieve the token natively within the API. Since it's data relating to google's auth'ing process, and since it might go stale if you store it, it seems best to just let them handle it and work with the API. The same source:
If you need to apply an access token to a new Google_Client object—for example, if you stored the access token in a user session—use the setAccessToken method:
$client->setAccessToken($access_token);
$client->getAccessToken();
I am using LinkedIn API to pull updates from there and display on the website. While using OAuth, I am storing the token in a file and then pull it from there again to prevent the login popup. However, I am not clear once my token expires how will it get refreshed. Following is how I am reading the token from the file -
$config = json_decode(file_get_contents(".service.dat"));
if( isset($config->key) && isset($config->secret) ) {
$this->access_token = new OAuthConsumer($config->key, $config->secret);
}
For authentication I have following to get request token -
function getRequestToken()
{
$consumer = $this->consumer;
$request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $this->request_token_path);
$request->set_parameter("oauth_callback", $this->oauth_callback);
$request->sign_request($this->signature_method, $consumer, NULL);
$headers = Array();
$url = $request->to_url();
$response = $this->httpRequest($url, $headers, "GET");
parse_str($response, $response_params);
$this->request_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
}
After generating token, I am generting authorize url:
function generateAuthorizeUrl()
{
$consumer = $this->consumer;
$request_token = $this->request_token;
return $this->authorize_path . "?oauth_token=" . $request_token->key;
}
LinkedIn documentation states following about refresh token:
Refreshing an access token is very simple and can happen without an
authorization dialog appearing for the user. In other words, it's a
seamless process that doesn't affect your application's user
experience. Simply have your application go through the authorization
flow in order to fetch a new access token with an additional 60 day
life span.
I am not clear what that means. If I have to redo all the way from obtaining request token again then wouldn't that require me to make http request again and having to popup the login screen? How do I avoid it? Will appreciate suggestion.
Thanks.
Found out. Authorization URL:
https://www.linkedin.com/oauth/v2/authorization
followed by the access token url:
https://www.linkedin.com/oauth/v2/accessToken
was all that I really had to do (passing with the right parameters).
There is also a endpoint to refresh the token once it expire, here is the documentation of the way to do it: https://learn.microsoft.com/en-us/linkedin/shared/authentication/programmatic-refresh-tokens
If You go through the documentation
Linkedin does not provide refresh token you need to again go through the workflow.
Here is the Short Explanation:
To refresh an Access Token, simply go through the authorization process outlined in this document again to fetch a new token. During the refresh workflow, provided the following conditions are met, the authorization dialog portion of the flow is automatically skipped and the user is redirected back to your callback URL, making acquiring a refreshed access token a seamless behind-the-scenes user experience
Refresh your Access Tokens
it is kinda dum, but i'm really stuck on this. Im trying to use https://github.com/artdarek/oauth-4-laravel for FB login on my Laravel project. I'm looking at these PHP code samples:
...
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken( $code );
...
What is $code referring to? I just can't figure this out :/
My idea is to use JavaScriptSDK for user login and after that send a request with just-logged-in userID to my server where additional user info should be acquired from FB and stored. So is them $code some attribute from authResponse?
$code is a query-string-supplied variable that is set by Facebook when they redirect your user back to your application, after they've authorized you to use their account.
The application then makes an API call to Facebook with that code in order to get the OAuth token.
I'm trying to create a cron job with a php script for retrieving info about stats of a Fan Pages and I have some questions:
have I to log a user to get the access token and use the Facebook API?
Which kind of token must to use? App token? Page Token?
I've read in several posts in Stackoverflow that only the Page Access token is necessary, but I have no success:
Request: /419788471442322/?fields=access_token
Response: Unsupported get request.
This is the code
//get the app access token
$facebook->setAccessToken($facebook->getAccessToken());
//Format the api call
$fields = array('access_token');
$page_info = $facebook->getInsights($id,"",$fields);
//display the result
print_r($page_info);
public function getInsights($id, $nameapi, $fields = array(), $limit = null)
{
if (isset($fields)) $fields = implode(",",$fields);
if (isset($limit)) $limit = "&limit=".$limit;
try {
echo '/'.$id.'/'.$nameapi.'?fields='.$fields.$limit;
$fbdata = $this->facebook->api('/'.$id.'/'.$nameapi.'?fields='.$fields.$limit);
} catch (FacebookApiException $e) {
$fbdata = $e->getMessage();
}
return $fbdata;
}
By default, the App Access Token will be used and you don´t need to set it with setAccessToken.
The App Access Token is good enough for basic infos and the Page feed, but for getting access to the Insights you need a Page Access Token and that´s a bit more complicated. Actually, in a Cron Job you would need a Page Access Token that is valid forever, basic ones are only valid for 2 hours. "Extended Page Access Token" is exactly what you need.
More info about Access Tokens and how to get an Extended Page Access Token:
https://developers.facebook.com/docs/facebook-login/access-tokens/
http://www.devils-heaven.com/facebook-access-tokens/
I'm using https://github.com/abraham/twitteroauth library. I already created my app on Twitter, the callbacks are working fine (even on localhost), but one thing that is bugging me is HOW the auto-login happens? I know there's "user_id" that is stored in the MYSQL database, along with oauth_token and oauth_token_secret, but how do I obtain user_id as soon as the user enters the site, so I can query the database to see if it already exists and what not, without having to popup the authorize twitter popup then reaching the callback, over and over again?
I've seen a lot of questions like this one, but no one ever answered it in a satisfying way.
The ones that should be saved to be used in verifying the user automatically are the oauth_access_token and oauth_access_secrete . Have you managed to get them from twitter?
The Oauth steos are:
Acquiring a request token
Sending the user to authorization
Exchanging a request token for an access token
Using out-of-band/PIN code mode for desktop & mobile applications
please refer to :
http://dev.twitter.com/pages/auth
actually, it needs to be a mix of PHP own $_SESSION with OAuth callbacks. After the callback, set the current user ID you inserted on the database or query for "user_id" from Twitter OAuth response (that you should ALSO store on the database, along with the username), then use that for future reference, and using $_SESSION containing the registered user data on your own database.
So, for a quick example
function action_login()
{
if ( ! $this->user->is_logged())
{
// Create TwitterOAuth object with our Twitter provided keys
$tOAuth = new TwitterOAuth($this->config->get('consumer_key'), $this->config->get('consumer_secret'));
// Generate request tokens
$requestToken = $tOAuth->getRequestToken(url::site('auth/twitter','http'));
$_SESSION["oauth_token"] = $requestToken["oauth_token"];
$_SESSION["oauth_token_secret"] = $requestToken["oauth_token_secret"];
// Display Twitter log in button with encoded link
$this->view->set('url', $tOAuth->getAuthorizeURL($requestToken["oauth_token"]));
$_SESSION['current_url'] = Request::detect_uri();
}
echo $this->view->render();
}
public function action_twitter()
{
if ( empty($_GET["denied"]) && isset($_GET["oauth_token"]))
{
if ($_GET["oauth_token"] == #$_SESSION["oauth_token"])
{
// Use generated request tokens (from session) to construct object
$tOAuth = new TwitterOAuth($this->config->get('consumer_key'), $this->config->get('consumer_secret'), $_SESSION["oauth_token"], $_SESSION["oauth_token_secret"]);
// Retrieve access token from Twitter
$accessToken = $tOAuth->getAccessToken();
// Check we have valid response
if(is_numeric($accessToken["user_id"])) {
// Remove request token session variables
if ($this->user->loaded() || $this->user->where('user_id', '=', $accessToken['user_id'])->find()->loaded())
{
$this->user->values(array(
'oauth_token' => $accessToken['oauth_token'],
'oauth_token_secret' => $accessToken['oauth_token_secret'],
'screen_name' => $accessToken['screen_name'],
))->update();
}
else
{
$this->user->values(array(
'user_id' => $accessToken['user_id'],
'oauth_token' => $accessToken['oauth_token'],
'oauth_token_secret' => $accessToken['oauth_token_secret'],
'screen_name' => $accessToken['screen_name'],
))->create();
}
unset($_SESSION["oauth_token"]);
unset($_SESSION["oauth_token_secret"]);
echo $this->view->render();
// Redirect to main page
}
}
}
$this->request->redirect($_SESSION['current_url']);
}
so basically, the AUTO LOGIN (like the user is already logged to twitter, and already registered to your website) can't be done without him clicking the LOGIN WITH TWITTER button, unless you set the lifetime of your $_SESSION pretty high (like it happens with twitpic for example).
$this->user->is_logged() is checking for $_SESSION['id'] (auto increment on MYSQL) and $_SESSION['twitter']['user_id'] from twitter info
EDIT: Also, the quickest and cleanest way to do it, is to make an AJAX call on the page load with the Twitter credentials using the Javascript SDK, then set the $_SESSION variables with the info the SDK provided.