How to use basic authentication in slim php? - php

I am using slim framework to write my own API and everything is just fine but when I add the slim-basic-auth library to secure my API and test it .... I always get this error :
Uncaught Error: Class 'Tuupola\Middleware\HttpBasicAuthentication' not found in
D:\xampp\htdocs\mydatabase\public\index.php:22
Any help with that please ?
I installed the library and use it just like in tutorial
$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
"secure"=>false,
"users" => [
"userName##" => "password##" ]
]));

you are missing backslash
new Tuupola\Middleware\HttpBasicAuthentication
=>
new \Tuupola\Middleware\HttpBasicAuthentication

For anyone dealing with this issue: In addition to registering the middleware in your Middlewares.php (or where your $app = new Slim\App; is defined):
return static function (App $app, Closure $customErrorHandler): void {
<...>
$app->add(new \Tuupola\Middleware\HttpBasicAuthentication([
"users" => [
"somebody" => "passw0rd"
]
]));
};
If you're using fast CGI you must add this line to your public/.htaccess file to avoid getting 401 even with valid auth:
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Source: https://bugs.php.net/bug.php?id=67883

Related

Twitter API asatymic/twitter with Laravel 8

I followed his readme and I have done composer dump-autoload a million times, but still I receive an error. Don't know what i am making wrong. I am trying to use v2 version of twitter api. Please help me anyone.
In config/app.php:
'providers' => [
...
Atymic\Twitter\ServiceProvider\LaravelServiceProvider::class,
],
'aliases' => [
...
'Twitter' => Atymic\Twitter\Facade\Twitter::class,
],
In my controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Twitter;
class HomeController extends Controller {
public function index() {
$tweets = Twitter::getUserTimeline([
'screen_name' => 'xxxxxxx',
'count' => 10,
'format' => 'json'
]);
dd($tweets);
return view('home');
}
public function about() {
return view('about');
}
}
But I am getting this error:
Error
Call to undefined method Atymic\Twitter\Service\Accessor::getUserTimeline()
Look like you have to import facade
Instead of this
use Twitter;
Import this
use Atymic\Twitter\Facade\Twitter;
If you are using alias then run following command
php artisan config:clear
composer dump-autoload
php artisan optimize
Please look to the twitter api version which you have defined in the .env. you may need to use 1.1 and you are using v2
I think getUserTimeLine is available for version 1.1, and I think as the readme says you can use userTweets for v2

Laravel 8: Google Authorization Error 400

I'm using Laravel 8 to develop my project and I would like to use Google authentication system for my users to login.
So I downloaded package via composer require laravel/socialite command and added my information on .env:
GOOGLE_CLIENT_ID=example
GOOGLE_SECRET_KEY=example
GOOGLE_CALLBACK_URL=http://localhost:8000/auth/google/callback
And then I defined them on config/services.php:
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_SECRET_KEY'),
'redirect' => 'GOOGLE_CALLBACK_URL',
],
After that I created a controller on my auth/ directory which is called GoogleAuthController and goes like this:
use Laravel\Socialite\Facades\Socialite;
class GoogleAuthController extends Controller
{
public function redirect()
{
return Socialite::driver('google')->redirect();
}
}
And finally at my login blade:
Login with Google
But the problem with this is that it, whenever I test this, it says:
Error 400: invalid_request
Invalid parameter value for redirect_uri: Missing scheme: GOOGLE_CALLBACK_URL
So why am I receiving this error ? How to fix it ?
I really appreciate any idea or suggestion from you guys...
Thanks in advance.
Also if you want to take a look at my routes, here it is:
Route::get('/auth/google', [App\Http\Controllers\Auth\GoogleAuthController::class, 'redirect'])->name('auth.google');
Your config is wrong:
'redirect' => 'GOOGLE_CALLBACK_URL',
Should be
'redirect' => env('GOOGLE_CALLBACK_URL'),
And of course this redirect should point to Google, not your localhost.

Silex + HttpCacheServiceProvider: X-Symfony-Cache is always miss

I am just inserting the http cache on my silex project doing this:
// http cache
$this->register(new \Silex\Provider\HttpCacheServiceProvider(), array(
'http_cache.cache_dir' => $this->getConfig()['http_cache_service']['cache_dir'],
));
$this is an owner class that it extends from Silex Application.
And my routing is:
// homepage
$this->get('/', function (Request $request) use ($app) {
return new Response($app['twig']->render('index/index.html.twig', []), 200, [
'Cache-Control' => 's-maxage=500'
]);
})->bind('homepage');
And I run my application in this mode:
\Symfony\Component\HttpFoundation\Request::setTrustedProxies(array('127.0.0.1','localhost','192.168.2.11'));
$app['http_cache']->run();
I am following the steps written in http://silex.sensiolabs.org/doc/master/providers/http_cache.html
But, when I load the 'homepage' the X-Symfony-Cache is always miss.
I am using Apache2 with PHP7, and I don't have installed any inversed proxy as Varnish, because I understand that it is not mandatory because HttpCacheServiceProvider is enough by itself.

jwd filter does not work laravel 5

hello everyone :) in my laravel 5 file routes.php, and return this error
"BadMethodCallException compiled.php line in 6243:
Method filter does not exist."
but I worked correctly laravel 4.2
My code is:
Route::filter('authMobile', function($route, $request)
{
try{
$token = JWTAuth::getToken();
$user = JWTAuth::toUser($token);
$tokenStr = JWTAuth::getToken()->__toString();
if ($user->token != $tokenStr){
throw new Exception("Login Token don't match");
}
Session::put('user',$user->id);
}catch(Exception $e){
return Response::json(array(
'error' => true,
'message' => 'Invalid Session: '.$e->getMessage()
));
}
});
Thanks, regards
As you can see in the error:
"BadMethodCallException compiled.php line in 6243: Method filter does not exist."
This is about this part: Route::filter.
In Laravel 5 Middleware is the preferred way to handle it, instead of filters. They are not entirely gone:
Filters are not removed in Laravel 5. You can still bind and use your own custom filters using before and after.
source Upgrade Guide 4.2 > 5.0 (Scroll to
Route Filters) Here is explained how you can keep it working with Route, but I would suggest migration anyway;
The following Laravel features have been deprecated and will be removed entirely with the release of Laravel 5.2 in December 2015:
Route filters have been deprecated in preference of middleware.
source Upgrade Guide 5.1.0 (Scroll to Deprecations)
You can turn your authMobile into middleware by following the steps as posted in the docs, but I would suggest you update your package from composer too and take a look at the jwt-auth Authentication docs, which has detailed information on how to make it work in Laravel 5 with the already included middleware.
If you are using 0.5.* of jwt-auth you just enable them in your <appname>/Http/Kernel.php:
protected $routeMiddleware = [
...
'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
];
Then you can include it in Controller level for example:
public function __construct()
{
// Here we can say we want to jwt auth all resource functions except index and show.
$this->middleware('jwt.auth', ['except' => ['index','show']]);
}
Or in your routes.
Route::group(['middleware' => ['before' => 'jwt.auth', 'after' => 'jwt.refresh']], function () {
..etc
Instead of applying the filters like you would in Laravel 4.2

Unable to use Laravel / Socialite with Lumen

I try to use the package Laravel\Socialite in my system in Lumen (5.1)
I added this in the config\services.php file :
<?php
//Socialite
'facebook' => [
'client_id' => '##################',
'client_secret' => '##################',
'redirect' => 'http://local.dev/admin/facebook/callback',
],
In bootstrap\app.php file :
class_alias(Laravel\Socialite\Facades\Socialite::class, 'Socialite');
$app->register(Laravel\Socialite\SocialiteServiceProvider::class);
Then I created a controller for the facebook authentication :
<?php
namespace App\Http\Controllers\Facebook;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Contracts\Factory as Socialite;
class FacebookController extends Controller
{
public function redirectToProviderAdmin()
{
return Socialite::driver('facebook')->scopes(['manage_pages', 'publish_actions'])->redirect();
}
public function handleProviderCallbackAdmin()
{
$user = Socialite::driver('facebook')->user();
}
}
And in the routes.php :
$app->get('/admin/facebook/login', 'App\Http\Controllers\Facebook\FacebookController#redirectToProviderAdmin');
$app->get('/admin/facebook/callback', 'App\Http\Controllers\Facebook\FacebookController#handleProviderCallbackAdmin');
I just followed the documentation, changing according to my needs. When I go to page http://local.dev/admin/facebook/login, I get the following error :
Non-static method Laravel\Socialite\Contracts\Factory::driver() cannot be called statically, assuming $this from incompatible context
Indeed, according to the code, driver function must be instanciate.
EDIT : And if I try to instanciate this class, I get the following error :
Cannot instantiate interface Laravel\Socialite\Contracts\Factory
How do you make this module to work?
here's how that works in my case
in services.php file
'facebook' => [
'client_id' => '***************',
'client_secret' => '***************',
'redirect' => ""
],
i left redirect empty cause my site is multilingual (so, it fills in a bit later with sessions). if you use only one language, put there your callback absolute path. for example
"http://example.com:8000/my-callback/";
also check your config/app.php. in providers array
Laravel\Socialite\SocialiteServiceProvider::class,
in aliases array
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
my routes look like this
Route::get('facebook', 'Auth\AuthController#redirectToProvider');
Route::get('callback', 'Auth\AuthController#handleProviderCallback');
here's auth controllers methods. put in top
use Socialite;
//იობანი როტ
public function redirectToProvider(Request $request)
{
return Socialite::with('facebook')->redirect();
}
public function handleProviderCallback(Request $request)
{
//here you hadle input user data
$user = Socialite::with('facebook')->user();
}
my facebook app
giga.com:8000 is my localhost (so its the same localhost:8000)
as you can see in Valid OAuth redirect URI, you should put there your callback. in my case i use three urls cause i have three languages. in your case it should be just
http://your-domain-name.com:8000/callback
if you work on localhost, you should name your domain in config/services.php
mine look like this
'domain' => "your-domain.com",
after everything run these commands
php artisan cache:clear
php artisan view:clear
composer dump-autoload
restart your server, clear your browser cookies. hope it helps

Categories