Symfony 2 - FOSOAuthServerBundle - can we authorize manually? - php

I'm trying to use FOSOAuthServerBundle. It works pretty well but I try to make it works in API...
When I register a new user I create a new client and I would like to give him authorization directly.
The request of the access_token will be done when the user will log in...
The problem, the example given in the documentation, it makes a redirection to an authorization page, and after it will redirect to an URL...
It would be great to it without any redirection, only to make the authorization...
Part of my register code :
$user->setUsername($name);
$user->setEmail($email);
$encoder = $this->get('security.encoder_factory')->getEncoder($user);
$password_user = $encoder->encodePassword($password, $user->getSalt());
$user->setPassword($password_user);
$clientManager = $this->get('fos_oauth_server.client_manager.default');
$client = $clientManager->createClient();
$client->setRedirectUris(array('http://localhost:8888/app_dev.php'));
$client->setAllowedGrantTypes(array('token', 'authorization_code'));
$clientManager->updateClient($client);
$user->setClient($client);
// Here we would like to authorize the user witout redirection :
return $this->redirect($this->generateUrl('fos_oauth_server_authorize', array(
'client_id' => $client->getPublicId(),
'redirect_uri' => 'http://localhost:8888/app_dev.php',
'response_type' => 'code'
)));
I would like to authorize without any redirection... Because it's in API :/ , so no URL...
Is there another way to authorize ?
Thanks

Related

ETSY Api PHP Obtaining Token Credentials

I'm using y0lk package to help me with OAuth1 and ETSY App, I managed to get the temporary credentials, but can't get my hand on Access tokens.
here's what I do :
$client = new Etsy([
'identifier' => '*********************',
'secret' => '*********',
'scope' => 'listings_r transactions_r',
'callback_uri' => 'http://*********.loc/slider/'
]);
$tempCred = $client->getTemporaryCredentials();
$tmpSecret = $tempCred->getSecret();
$tmpId = $tempCred->getIdentifier();
// Redirect to Etsy Autorisation login page
$redirect_url = $client->getAuthorizationUrl($tempCred);
$accessTokens = $client->getTokenCredentials($tempCred, $tmpId, $_GET['oauth_verifier']);
Ok, I don't know how to do, because to obtain the oauth verifier ( and do the $_GET['oauth_verifier']), I have to go by the login page, and then, to get the access token, I need my temp credentials, but to get then I 'll have to go again by new Etsy and this is why I always got the token revoked error..
I'm beginner, in PHP and with API, if someone see other mistakes in my way to do this, feel free to point them out for me :)
Thank you for your time.

Laravel JWT Token Always Blacklisted

I am using the tymondesigns/jwt-auth package for my app. I use customClaims to make my token.
Here is the code for login :
$token_data = [
'iss' => new Issuer('AreteHCM'),
'iat' => new IssuedAt(Carbon::now()) ,
'exp' => new Expiration(Carbon::now()->addDays(1)),
'nbf' => new NotBefore(Carbon::now()),
'sub' => new Subject('AreteHCMS'),
'jti' => new JwtId('AreteHCM'),
'user_data' => $user->user,
'menu_access' => $menu_access,
'login_time' => Carbon::now(),
];
$customClaims = JWTFactory::customClaims($token_data);
$payload = JWTFactory::make($customClaims);
$token = JWTAuth::encode($payload)->get();
For Logout, I invalidate the token, so the token can not be used anymore after the user logout.
JWTAuth::invalidate(JWTAuth::getToken());
I'm creating API (Backend) and the front end team using Angular. Eveythings went smooth, until the user logout and try to login again. After login, the user get the new account, but when he/she wants to access my middleware always rejects the token, it says that the token is blacklisted.
Here is my middleware :
$token = JWTAuth::getToken();
$data = JWTAuth::getPayload($token)->toArray();
It always shows error :
The token has been blacklisted in file C:\xampp\htdocs\aretehcm\vendor\tymon\jwt-auth\src\Manager.php on line 109
What I want to approach is :
User login get new token to access the API (every API request requires header auth Bearer token)
User logout will invalidate the token, so the token can not be used anymore to access the API
User login will get a new token so he/she can access the API
Is there any misconception from me about the JWT-API architecture ?
Thank you in advance for your replies and answers.
A quick google search pointed me towards this solution:
https://github.com/tymondesigns/jwt-auth/issues/983#issuecomment-275884324

Problems with facebook php sdk v4

I am trying to get facebook php sdk v4 to work with my app. I am using Drupal and an nginx server with phpfpm.
When I try to get the session from facebook sdk, I get the error - Missing redirect uri parameter. While debugging, I found 2 strange things are happening -
1) If I copy and paste the get url(generated by the sdk) in my browser, a valid access token is returned.
2) If I change the method for retrieving the access token from GET(default) to POST in the sdk, a valid access token is returned to my app.
Also, when using the access token I received from POST call, if I make further GET requests to the graph api, none of them work.
However, if I make a POST request, such as posting to my wall, it works.
Also it should be noted that the sdk is internally using curl to make all requests.
Edit :
Code Example -
To generate login url
$helper = new \Facebook\FacebookRedirectLoginHelper($this->redirectUrl);
$loginUrl = $helper->getLoginUrl(array('public_profile', 'email', 'user_friends', 'publish_actions'));
Now the person is taken to facebook for authentication and redirected to my redirect url. Here the code is -
$helper = new \Facebook\FacebookRedirectLoginHelper($this->redirectUrl);
$session = helper->getSessionFromRedirect();
Since getSessionFromRedirect internally uses a GET call, it doesn't work for me. When I change the sdk code to use POST, a valid access token is returned.
Also when I get a valid session using a POST request, this works
$response = (new FacebookRequest(
$session, 'POST', '/me/feed', array(
'link' => 'www.example.com',
'message' => 'User provided message'
)
))->execute()->getGraphObject();
But this doesn't work -
$user_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
echo "Name: " . $user_profile->getName();
Clearly there seems to be an issue with all the GET requests. Any hints on what can be the problem?
Solved the problem finally. Turns out drupal is changing the & in url for GET requests to & .
Related to this .

Facebook login fails on website with SSL

We're building a web app in PHP. We've set up SSL certificate and right after that the FB login stopped working. When the script tries to get user ID, exception is thrown
An active access token must be used to query information about the current user.
I'm 100% positive the SSL is the problem because it works fine on my localhost and it also worked on the production before setting up the SSL.
We're using Facebook PHP SDK. Here is the first part (getting login url)
$facebook = new Facebook([
"appId" => "APP_ID",
"secret" => "SECRET"
]);
$permissions = ["email", "user_birthday", "publish_stream", "offline_access"];
$loginURL = $facebook->getLoginUrl([
"scope" => join(",", $permissions),
"redirect_uri" => "REDIRECT_URI"
]);
// redirect to $loginURL
And here's the callback
$facebook = new Facebook([
"appId" => "APP_ID",
"secret" => "SECRET"
]);
$userID = $facebook->getUser();
$token = $_GET['code'];
if(isset($userID) && isset($token)) {
// ... some cool stuff
} else {
// error, something happened
}
Thanx for help
EDIT: I was getting the error because I was trying to get details about user by the $userID. Problem was, the $userID is always 0 so no wonder I got error. Somehow I can't get user's ID on the website with SSL...
OK in the end I found the cause of my problems and it was realy stupid (like almost always, right?). When I was building the callback URL that is sent as an argument to the FB login page, I was getting the base url with a method from the framework I use. For some reason it gave me domain.com:443/ instead of domain.com/. After I fixed it, it suddenly works.
In mu case it was the WWW that was missing from the redirect URL. SSL cert was working only with it

facebook php sdk - Error #200 when trying to use setExtendedAccessToken

I have been trying for several days now to successfully post to a client's Facebook Page wall from their website. I need to be able to do this without having a user logged in, which I was able to achieve with an extended access token generated by going to the URL provided in the docs.
What I am trying to do is to fetch an extended token using the PHP SDK as in this question - Facebook PHP SDK: getting "long-lived" access token now that "offline_access" is deprecated, however I receive the following error:
(#200) The user hasn't authorized the application to perform this action
The debug of the auth token generated by the Graph API Explorer shows myself as the User and includes the needed manage_pages and status_update scopes. However, if I run me/accounts, the perms array does not list these under the data for the page in question - not sure if this is relevant.
Here is the code that I have attempted to use:
$facebook = new Facebook(array('appId' => 'xxxxxxx', 'secret' => 'xxxxxx'));
$pageID = 'xxxxxxxx';
$facebook->setExtendedAccessToken();
$accessToken = $facebook->getAccessToken();
try {
$page_info = $facebook->api("/$pageID?fields=access_token");
print_r ($page_info);
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
if( !empty($accessToken) ) {
$args = array(
'access_token' => $accessToken,
'message' => "Catch phrase!"
);
$facebook->api("/$pageID/feed","post",$args);
} else {
// Handle error
}
UPDATE
I found that if I echoed the output of getAccessToken() the result was the app ID and the secret separated by an | - is this what I should be receiving? Seems odd to me since all of the other tokens I have seen are random and much longer.
ANY help at all would be appreciated, I have wasted so much time on this so far. It just seems to work for everyone else.
UPDATE 2
Hi Warren! Looks like you're new around these parts, welcome! Thanks for your research into this, do I need to save these tokens into a DB table and check to see if they are expired every time I try to post? I am ONLY posting to a Page as the Page, apparently this requires the Page access_token rather than what I am assuming is the USER access_token. I believe I also read somewhere that the Page access token never expires, although it changes if I refresh the Graph API Explorer page or request a new user token. Very puzzling.. do not know if I even need to deal with getting new tokens in this app or just use a Page access_token that appears to work?
Also just looking at the base_facebook.php file and the following function:
/**
* Returns the access token that should be used for logged out
* users when no authorization code is available.
*
* #return string The application access token, useful for gathering
* public information about users and applications.
*/
protected function getApplicationAccessToken() {
return $this->appId.'|'.$this->appSecret;
}
Shows what you are experiencing the function setExtendedAccessToken() calls getAccessToken() which calls the function above to do the following inside setExtendedAccessToken:
$access_token_response = $this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array(
'client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
'grant_type' => 'fb_exchange_token',
'fb_exchange_token' => $this->getAccessToken(),
)
);
the return of this function is then {"error":{"message":"No user access token specified","type":"OAuthException","code":1}} but because there is no access_token the function just returns false
the fb_exchange_token can not be the app id and app secret combined.
I have done some testing and what I have found out is if you get the user to login, you can get there access token. If you pass this token into setAccessToken then run setExtendedToken. If you then save the toke by running getAccessToken you can use this token later when the user is logged out.
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // save this for later use
You need to get the user to login to ask them for permission to get access to there account. If you need to get access to a facebook page make sure they are an admin and ask for the manage_page permission.
Hope this helps
From what I have found so far the extended token that is returned when the user is logged in does not expire as you do not get back a unix timestamp so you would have no way of knowing when it expires.
This is what I have done in my application.
Request the user to login to facebook and except the access permissions. Use getAccessToken to get the current access token. With this I pass into getExtendedAccessToken then run getAccessToken again to finally get the extended access token which I store in a database for later use.
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$params = array(
'scope'=>'publish_stream,manage_pages'
);
$loginUrl = $facebook->getLoginUrl($params); // Use this to request them to login in then when they are do the following you will need them to return to your app
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // store $access_token for later use

Categories