Basecamp API authentication with OAuth2: internal checksum failed error - codeigniter

I'm trying to write a CodeIgniter controller to handle OAuth2 authentication for the 37signals' Basecamp API.
The problem is I keep encountering the 'internal checksum failed' error, when trying to connect (via cURL) to https://launchpad.37signals.com/authorization.json, providing the Auth Token in a HTTP header.
Here's the index and _authcode functions from my controller class:
<?php
// constants:
// BC_REQUEST_URL = 'https://launchpad.37signals.com/authorization/new'
// BC_TOKEN_URL = 'https://launchpad.37signals.com/authorization/token'
// ...
public function index() {
// if get data is set.
if ($this->input->get()) {
// if auth code is provided via GET, switch to _authcode method.
if ( $code = $this->input->get('code') ) {
return $this->_authcode($code);
}
// On error, kill yourself.
if ( $error = $this->input->get('error') ) {
die($error);
}
}
// redirect to 37 signals to get an authcode
header("Location: ".BC_REQUEST_URL."?type=web_server&client_id=".BC_CLIENT_ID."&redirect_uri=".BC_REDIRECT_URL."");
}
// handles the Authentication code that is returned by 37 Signals.
private function _authcode($code) {
// set vars to POST
$vars = array(
'type' => 'web_server',
'client_id' => BC_CLIENT_ID,
'redirect_uri' => BC_REDIRECT_URL,
'client_secret' => BC_CLIENT_SECRET,
'code' => $code
);
// make a request for the access_token
$url = BC_TOKEN_URL;
$c = curl_init($url);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, http_build_query($vars));
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($c));
curl_close($c);
unset($c,$url);
// get the access vars from this request
$expiry_seconds = $response->expires_in; // default: 1209600 (14 days)
$refresh_token = $response->refresh_token;
$access_token = $response->access_token;
unset($response);
// make a separate request to get user info for current user.
$url = "https://launchpad.37signals.com/authorization.json";
$c = curl_init($url);
curl_setopt($c, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer <$access_token>",
"Content-Type: application/json; charset=utf-8",
"User-Agent: MyApp (http://myapp.example.com)"
));
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($c)); // reply from 37 signal auth
curl_close($c);
unset($c,$url);
echo "response obj = " . print_r($response,1);
/* prints: response obj = stdClass Object ( [error] => OAuth token could not be verified. The internal checksum failed, so the token data was somehow mangled or tampered with. ) */
// get the user data from this request
// $expires_at = $response->expires_at; // the timestamp for when this request expires
// $identity = $response->identity; // the current user
// $accounts = $response->accounts; // list of accounts we can access
// unset($response);
// store the response data to the database for easy recall.
// $this->db->query("REPLACE INTO `sometable` SET `key1`='value', `key2`='value');
}
// ...
?>

I ran into this error when saving the auth token in the database with varchar(255). Basecamp's auth token has some checksum data which brings the token over 255 characters.
You don't appear to be pulling it from a database in your example, so this might not affect you, however checking for Basecamp's token being cut off is what I would first look at.
Optionally, remove the <> characters around your $access_token when setting the Bearer header.

Related

problem with multiple HTTP requests in Laravel with Guzzle

I'm using Guzzle version 6.3.3. I want to make multiple HTTP requests from an external API. The code shown below worker perfect for me. This is just one single request.
public function getAllTeams()
{
$client = new Client();
$uri = 'https://api.football-data.org/v2/competitions/2003/teams';
$header = ['headers' => ['X-Auth-Token' => 'MyKey']];
$res = $client->get($uri, $header);
$data = json_decode($res->getBody()->getContents(), true);
return $data['teams'];
}
But now I want to make multiple requests at once. In the documentation of Guzzle I found out how to do it, but it still didn't work properly. This is the code I try to use.
$header = ['headers' => ['X-Auth-Token' => 'MyKey']];
$client = new Client(['debug' => true]);
$res = $client->send(array(
$client->get('https://api.football-data.org/v2/teams/666', $header),
$client->get('https://api.football-data.org/v2/teams/1920', $header),
$client->get('https://api.football-data.org/v2/teams/6806', $header)
));
$data = json_decode($res->getBody()->getContents(), true);
return $data;
I get the error:
Argument 1 passed to GuzzleHttp\Client::send() must implement interface Psr\Http\Message\RequestInterface, array given called in TeamsController.
If I remove the $header after each URI then I get this error:
resulted in a '403 Forbidden' response: {"message": "The resource you are looking for is restricted. Please pass a valid API token and check your subscription fo (truncated...)
I tried several ways to set X-Auth-Token with my API key. But I still get errors and I don't know many other ways with Guzzle to set them.
I hope someone can help me out :)
Guzzle 6 uses a different approach to Guzzle 3, so you should use something like:
use function GuzzleHttp\Promise\all;
$header = ['headers' => ['X-Auth-Token' => 'MyKey']];
$client = new Client(['debug' => true]);
$responses = all([
$client->getAsync('https://api.football-data.org/v2/teams/666', $header),
$client->getAsync('https://api.football-data.org/v2/teams/1920', $header),
$client->getAsync('https://api.football-data.org/v2/teams/6806', $header)
])->wait();
$data = [];
foreach ($responses as $i => $res) {
$data[$i] = json_decode($res->getBody()->getContents(), true);
}
return $data;
Take a look at different questions on the same topic (#1, #2) to see more usage examples.

Struggling to store token for AdSense API

I've successfully managed to connect to the AdSense API and run a report. However, it requires a log in each time I run it, so it won't run as a cron job.
I've found a few other questions related to this. Some advise a service account, while others point out that a service account does not work with AdSense. The proposed solution is to store a token on my server, but I've been struggling to get that to work. Here is my code so far (which works, but requires manual log in):
$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
$client->setApplicationName('My Application name');
$client->setClientId(' MY ID ');
$client->setClientSecret(' MY SECRET ');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey(' MY KEY '); // API key
$accountId = " MY ACCOUNT " ;
$adClientId = " MY CLIENT " ;
// $service implements the client interface, has to be set before auth call
$service = new Google_Service_AdSense($client);
if (isset($_GET['logout'])) { // logout: destroy token
unset($_SESSION['token']);
die('Logged out.');
}
if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) { // extract token from session and configure client
$token = $_SESSION['token'];
$client->setAccessToken($token);
}
if (!$client->getAccessToken()) { // auth call to google
$authUrl = $client->createAuthUrl();
header("Location: ".$authUrl);
die;
}
$startDate = '2015-11-01';
$endDate = 'today';
$optParams = array(
'metric' => array(
'EARNINGS'),
'dimension' => array('DATE'),
'sort' => '+DATE',
'filter' => array(
'CUSTOM_CHANNEL_NAME==Mega Seating Plan'
)
);
// Run report.
$report = $service->accounts_reports->generate($accountId, $startDate,
$endDate, $optParams);
if (isset($report) && isset($report['rows'])) {
// Get results.
foreach($report['rows'] as $row) {
$date = $row[0] ;
$earnings[$date] = $row[1] ;
}
} else {
print "No rows returned.\n";
}
Can anybody give me any pointers about how I can incorporate token storage into the above code, please?
Thank you to #jkns.co for the previous answer here which helped me to get it working.
Here's my final code:
$scriptUri = "I HAD TO PUT MY ABSOLUTE URL HERE, OTHERWISE THE CRON JOB WOULD LOOK IN THE WRONG PLACE" ;
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
$client->setApprovalPrompt ("force"); // This line had to be added to force the approval prompt and request a new token
$client->setApplicationName('My Application name');
$client->setClientId('BLAH');
$client->setClientSecret('BLAH');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('BLAH'); // API key
$accountId = "BLAH" ;
$adClientId = "BLAH" ;
// $service implements the client interface, has to be set before auth call
$service = new Google_Service_AdSense($client);
if (isset($_GET['logout'])) { // logout: destroy token
unset($_SESSION['token']);
die('Logged out.');
}
if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
// If it successfully authenticates, I request the refresh token
$refreshToken = $client->getRefreshToken();
storeRefreshToken($refreshToken) ; // This function stores the token in MySQL
}
else { // Otherwise it loads the refresh token from MySQL
$refreshToken = getRefreshToken() ;
$client->refreshToken($refreshToken);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) { // extract token from session and configure client
$token = $_SESSION['token'];
$client->setAccessToken($token);
}
if (!$client->getAccessToken()) { // auth call to google
$authUrl = $client->createAuthUrl();
header("Location: ".$authUrl);
die;
}

Lumen JWT send token with requests

Authentication is working, I have a few routes under auth middleware, Whenever i request it throws :
{
"message": "Failed to authenticate because of bad credentials or an invalid authorization header.",
"status_code": 401
}
How can i send the token with the request like :
Authorization bearer {{Long token}}
It works with `postman`, How can i send the token with request header, Or in any other best way.
Route :
$api->get('/categories', [
'uses' => 'App\Http\Controllers\CategoryController#index',
'as' => 'api.categories',
]);
Method :
public function index() {
$lessons = \App\Category::all();
$token = JWTAuth::getToken(); // $token have jwt token
return response()->json([
'data' => $lessons,
'code' => 200,
]);
}
The question was pretty vague to answer. Please be more specific from next time. From your comments i could finally realise that you want to consume the api from a mobile app.
You need to return the token generated for an user either during login or during registration or any other authentication method/route you have. The mobile app needs to read this response and store the token locally. Then the app needs to inject this token in the request header for every single request. That's the normal api token workflow.
The app should also be coded to read the error response from requests and if it returns errors for expired or invalid token, the app needs to clear the locally stored token and then request the user to login again to generate a fresh token.
you can use : https://github.com/tymondesigns/jwt-auth
requriment :
Laravel 4 or 5 (see compatibility table)
PHP 5.4 +
Steps:
1 : add below line in composer.json in require array
"tymon/jwt-auth": "0.5.*"
2 : run "composer update" in your terminal
3 : after this you have to register service provider
go to config/app.php
and add 'Tymon\JWTAuth\Providers\JWTAuthServiceProvider' this in provider array
and 'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth' , 'JWTFactory' => 'Tymon\JWTAuth\Facades\JWTFactory' this to aliases array
4 : publish pacakge :
"php artisan vendor:publis --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
5 : generate secrate key in config file
'php artisan jwt:generate'
6 : for addition configuration : https://github.com/tymondesigns/jwt-auth/wiki/Configuration
Usage :
AuthenticateController.php
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
class AuthenticateController extends Controller
{
public function authenticate(Request $request)
{
// grab credentials from the request
$credentials = $request->only('email', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return response()->json(compact('token'));
}
}
You can also skip user authentication and just pass in a User object. e.g.
// grab some user
$user = User::first();
$token = JWTAuth::fromUser($user);
The above two methods also have a second parameter where you can pass an array of custom claims. e.g.
$customClaims = ['foo' => 'bar', 'baz' => 'bob'];
JWTAuth::attempt($credentials, $customClaims);
// or
JWTAuth::fromUser($user, $customClaims);
create token based on anything
$customClaims = ['foo' => 'bar', 'baz' => 'bob'];
$payload = JWTFactory::make($customClaims);
$token = JWTAuth::encode($payload);
d

How to return json reponse from laravel to angular?

I have this in controller :
public function index(Request $request){
$email = $request->email;
$password = $request->password;
if (!$email || !$password) {return redirect()->back();}
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
$this->loggedUser = Auth::user();
if($this->loggedUser){
return response()->json(['isLoggedIn' => true],200);
}
}
return response()->json(['isLoggedIn' => false],200);
}
In angular i have this:
Login (body: Object): Observable<Login[]> {
let bodyString = JSON.stringify(body); // Stringify payload
let options = new RequestOptions({ headers: this.headers }); // Create a request option
return this.http.post('/index', body, options) // ...using post request
.map(response => {return response} ,console.log('aaa')) // ...and calling .json() on the response to return data
.catch((error:any) => Observable.throw(error.json().error || 'Server error' )); //...errors if any
}
Problem is that when i open in browser response i get this:
Deprecated: Automatically populating
$HTTP_RAW_POST_DATA is deprecated and will be removed in a future
version. To avoid this warning set 'always_populate_raw_post_data' to
'-1' in php.ini and use the php://input stream instead. in
Unknown on line 0 Warning: Cannot
modify header information - headers already sent in Unknown on
line 0 {"isLoggedIn":false
}
Any suggestion how can fix that so that in response i get json?
This is a warning you get from PHP5.6 and it will be obscuring your data that you are getting back from your request.
Go into your php.ini file and update this line
;always_populate_raw_post_data = -1
to
always_populate_raw_post_data = -1
Don't forget to restart apache when you have made this update

Curl PUT Request and empty request data (rest api)

I am trying to make a PUT request, in order to edit some user's data, but I am receiving empty data instead of what I'm sending through my request.
I have tried with postman (a chrome plugin) and with a custom php snippet:
?php
$process = curl_init('http://localhost/myapp/api/users/1.json');
$headers = [
'Content-Type:application/json',
'Authorization: Basic "...=="'
];
$data = [
'active' => 0,
'end_date' => '01/01/2018'
];
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_PUT, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, $data);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($process);
curl_close($process);
print_r($return);
This is the code that I'm using cakephp-side:
class UsersController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
....
public function edit($id = null)
{
debug($_SERVER['REQUEST_METHOD']);
debug($this->request->data);
die;
}
....
And this is what it outputs:
/src/Controller/UsersController.php (line 318)
'PUT'
/src/Controller/UsersController.php (line 319)
[]
I am confused... similar code is working for a POST request and the add action... what is wrong with this code?
Two problems.
When using CURLOPT_PUT, you must use CURLOPT_INFILE to define the data to send, ie your code currently doesn't send any data at all.
CURLOPT_PUT
TRUE to HTTP PUT a file. The file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE.
http://php.net/manual/en/function.curl-setopt.php
You are defining the data as an array.
CURLOPT_POSTFIELDS
[...] If value is an array, the Content-Type header will be set to multipart/form-data.
http://php.net/manual/en/function.curl-setopt.php
So even if the data would be sent, it would be sent as form data, which the request handler component wouldn't be able to decode (it would expect a JSON string), even if it would try to, which it won't, since your custom Content-Type header would not be set unless you'd pass the data as a string.
Long story short, use CURLOPT_CUSTOMREQUEST instead of CURLOPT_PUT, and set your data as a JSON string.
curl_setopt($process, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($process, CURLOPT_POSTFIELDS, json_encode($data));
Your Postman request likely has a similar problem.

Resources