Laravel implementing simple MiddleWare doesn't work - laravel

In my web application i'm trying to check local in URLs, for example:
In this URL as http://www.sample.com/aboutUs we don't have any locale such as en,ru or etc like: http://www.sample.com/en/aboutUs.
In my web app I implemented simple middleware to check that and fix URL when URLs don't have them:
class language
{
public function handle($request, Closure $next)
{
dd($request);
$locale = $request->segment(1);
if (!array_key_exists($locale, config('app.locales'))) {
$segments = $request->segments();
$segments[0] = config('app.fallback_locale');
return redirect(implode('/', $segments));
}
app()->setLocale($locale);
return $next($request);
}
}
Which that registered into:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\Language::class,
...
],
'api' => [
'throttle:60,1',
'bindings',
],
];
protected $routeMiddleware = [
'language' => \App\Http\Middleware\Language::class,
...
];
This middleware only work when we have locale in URL and my code as:
Route::get('/showContent/aboutUs', ['middleware' => 'language', function()
{
dd('asda');
//
}]);
This doesn't work and I don't see any dd output
1:
Route::group(['middleware' => 'web'], function () {
Route::get('/showContent/aboutUs', 'HomeController#aboutUs');
});
2:
Route::group(['middleware' => 'language'], function () {
Route::get('/showContent/aboutUs', 'HomeController#aboutUs');
});
for all my solutions i get this output:
Sorry, the page you are looking for could not be found.

Related

Laravel Localization Routes in Jetstream & Fortify

I am using Laravel 8 with the Jetstream and Fortify authentication module. All the auth module works, on the other hand I was in the process of making the site in multi-languages, and I found myself with errors in authentication.
My problem today is the following, when the user finishes registering, he must check his email, or Laravel tells me the following error :
> Illuminate\Routing\Exceptions\UrlGenerationException
Missing required parameter for [Route: verification.verify] [URI: {locale}/email/verify/{id}/{hash}] [Missing parameter: locale].
But, for the others routes like /en/login, /en/register, /en/user/profile ..., they work fine ! The error is just for the email validation, please help, thanks. To have control over my authentication routes, I ignored the default JetStream & Fortify routes in the app/providers
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function(){
return redirect()->route('home-locale', app()->getLocale());
})->name('home');
Route::group([
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}']], function(){
Route::get('/', 'HomeController#index')->name('home-locale');
Auth::routes();
});
Route::get('/index', 'HomeController#index');
Route::post('/map-agents','MapController#ajaxRequestMap')->name('*','map.agents');
Route::post('/map-agents/agents','MapController#ajaxRequestAgent');
Route::group([
'middleware' => ['auth:sanctum', 'verified'],
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}']],
function (){
Route::get('/dashboard', 'DashboardController#index')->name('dashboard');
});
Route::group([
'middleware' => ['auth'],
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}']],
function (){
Route::resource('agents', AgentsController::class);
});
routes/fortify.php
<?php
use Illuminate\Support\Facades\Route;
use Laravel\Fortify\Features;
use Laravel\Fortify\Http\Controllers\AuthenticatedSessionController;
use Laravel\Fortify\Http\Controllers\ConfirmablePasswordController;
use Laravel\Fortify\Http\Controllers\ConfirmedPasswordStatusController;
use Laravel\Fortify\Http\Controllers\EmailVerificationNotificationController;
use Laravel\Fortify\Http\Controllers\EmailVerificationPromptController;
use Laravel\Fortify\Http\Controllers\NewPasswordController;
use Laravel\Fortify\Http\Controllers\PasswordController;
use Laravel\Fortify\Http\Controllers\PasswordResetLinkController;
use Laravel\Fortify\Http\Controllers\ProfileInformationController;
use Laravel\Fortify\Http\Controllers\RecoveryCodeController;
use Laravel\Fortify\Http\Controllers\RegisteredUserController;
use Laravel\Fortify\Http\Controllers\TwoFactorAuthenticatedSessionController;
use Laravel\Fortify\Http\Controllers\TwoFactorAuthenticationController;
use Laravel\Fortify\Http\Controllers\TwoFactorQrCodeController;
use Laravel\Fortify\Http\Controllers\VerifyEmailController;
Route::group([
'middleware' => config('fortify.middleware', ['web']),
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}']],
function () {
$enableViews = config('fortify.views', true);
// Authentication...
if ($enableViews) {
Route::get('/login', [AuthenticatedSessionController::class, 'create'])
->middleware(['guest'])
->name('login');
}
$limiter = config('fortify.limiters.login');
$twoFactorLimiter = config('fortify.limiters.two-factor');
Route::post('/login', [AuthenticatedSessionController::class, 'store'])
->middleware(array_filter([
'guest',
$limiter ? 'throttle:'.$limiter : null,
]));
Route::post('/logout', [AuthenticatedSessionController::class, 'destroy'])
->name('logout');
// Password Reset...
if (Features::enabled(Features::resetPasswords())) {
if ($enableViews) {
Route::get('/forgot-password', [PasswordResetLinkController::class, 'create'])
->middleware(['guest'])
->name('password.request');
Route::get('/reset-password/{token}', [NewPasswordController::class, 'create'])
->middleware(['guest'])
->name('password.reset');
}
Route::post('/forgot-password', [PasswordResetLinkController::class, 'store'])
->middleware(['guest'])
->name('password.email');
Route::post('/reset-password', [NewPasswordController::class, 'store'])
->middleware(['guest'])
->name('password.update');
}
// Registration...
if (Features::enabled(Features::registration())) {
if ($enableViews) {
Route::get('/register', [RegisteredUserController::class, 'create'])
->middleware(['guest'])
->name('register');
}
Route::post('/register', [RegisteredUserController::class, 'store'])
->middleware(['guest']);
}
// Email Verification...
if (Features::enabled(Features::emailVerification())) {
if ($enableViews) {
Route::get('/email/verify', [EmailVerificationPromptController::class, '__invoke'])
->middleware(['auth'])
->name('verification.notice');
}
Route::get('/email/verify/{id}/{hash}', [VerifyEmailController::class, '__invoke'])
->middleware(['auth', 'signed', 'throttle:6,1'])
->name('verification.verify');
Route::post('/email/verification-notification', [EmailVerificationNotificationController::class, 'store'])
->middleware(['auth', 'throttle:6,1'])
->name('verification.send');
}
// Profile Information...
if (Features::enabled(Features::updateProfileInformation())) {
Route::put('/user/profile-information', [ProfileInformationController::class, 'update'])
->middleware(['auth'])
->name('user-profile-information.update');
}
// Passwords...
if (Features::enabled(Features::updatePasswords())) {
Route::put('/user/password', [PasswordController::class, 'update'])
->middleware(['auth'])
->name('user-password.update');
}
// Password Confirmation...
if ($enableViews) {
Route::get('/user/confirm-password', [ConfirmablePasswordController::class, 'show'])
->middleware(['auth'])
->name('password.confirm');
Route::get('/user/confirmed-password-status', [ConfirmedPasswordStatusController::class, 'show'])
->middleware(['auth'])
->name('password.confirmation');
}
Route::post('/user/confirm-password', [ConfirmablePasswordController::class, 'store'])
->middleware(['auth']);
// Two Factor Authentication...
if (Features::enabled(Features::twoFactorAuthentication())) {
if ($enableViews) {
Route::get('/two-factor-challenge', [TwoFactorAuthenticatedSessionController::class, 'create'])
->middleware(['guest'])
->name('two-factor.login');
}
Route::post('/two-factor-challenge', [TwoFactorAuthenticatedSessionController::class, 'store'])
->middleware(array_filter([
'guest',
$twoFactorLimiter ? 'throttle:'.$twoFactorLimiter : null,
]));
$twoFactorMiddleware = Features::optionEnabled(Features::twoFactorAuthentication(), 'confirmPassword')
? ['auth', 'password.confirm']
: ['auth'];
Route::post('/user/two-factor-authentication', [TwoFactorAuthenticationController::class, 'store'])
->middleware($twoFactorMiddleware);
Route::delete('/user/two-factor-authentication', [TwoFactorAuthenticationController::class, 'destroy'])
->middleware($twoFactorMiddleware);
Route::get('/user/two-factor-qr-code', [TwoFactorQrCodeController::class, 'show'])
->middleware($twoFactorMiddleware);
Route::get('/user/two-factor-recovery-codes', [RecoveryCodeController::class, 'index'])
->middleware($twoFactorMiddleware);
Route::post('/user/two-factor-recovery-codes', [RecoveryCodeController::class, 'store'])
->middleware($twoFactorMiddleware);
}
});
routes/jetstream.php
<?php
use Illuminate\Support\Facades\Route;
use Laravel\Jetstream\Http\Controllers\CurrentTeamController;
use Laravel\Jetstream\Http\Controllers\Livewire\ApiTokenController;
use Laravel\Jetstream\Http\Controllers\Livewire\PrivacyPolicyController;
use Laravel\Jetstream\Http\Controllers\Livewire\TeamController;
use Laravel\Jetstream\Http\Controllers\Livewire\TermsOfServiceController;
use Laravel\Jetstream\Http\Controllers\Livewire\UserProfileController;
use Laravel\Jetstream\Http\Controllers\TeamInvitationController;
use Laravel\Jetstream\Jetstream;
Route::group(
[
'middleware' => config('jetstream.middleware', ['web']),
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}']],
function () {
if (Jetstream::hasTermsAndPrivacyPolicyFeature()) {
Route::get('/terms-of-service', [TermsOfServiceController::class, 'show'])->name('terms.show');
Route::get('/privacy-policy', [PrivacyPolicyController::class, 'show'])->name('policy.show');
}
Route::group(['middleware' => ['auth', 'verified']], function () {
// User & Profile...
Route::get('/user/profile', [UserProfileController::class, 'show'])
->name('profile.show');
// API...
if (Jetstream::hasApiFeatures()) {
Route::get('/user/api-tokens', [ApiTokenController::class, 'index'])->name('api-tokens.index');
}
// Teams...
if (Jetstream::hasTeamFeatures()) {
Route::get('/teams/create', [TeamController::class, 'create'])->name('teams.create');
Route::get('/teams/{team}', [TeamController::class, 'show'])->name('teams.show');
Route::put('/current-team', [CurrentTeamController::class, 'update'])->name('current-team.update');
Route::get('/team-invitations/{invitation}', [TeamInvitationController::class, 'accept'])
->middleware(['signed'])
->name('team-invitations.accept');
}
});
});
app/Http/Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Laravel\Jetstream\Http\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\SetLocale::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}
app/Http/Middleware/setLocale.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class SetLocale
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
$languages = array_keys(config('app.languages'));
$route = $request->route();
if (request('change_language')) {
session()->put('language', request('change_language'));
$language = request('change_language');
if (array_key_exists('locale', $route->parameters) && $route->parameters['locale'] != $language)
{
$route->parameters['locale'] = $language;
if (in_array($language, $languages)) {
app()->setLocale($language);
}
return redirect(route($route->getName(), $route->parameters));
}
} elseif (session('language')) {
$language = session('language');
if (array_key_exists('locale', $route->parameters) && $route->parameters['locale'] != $language && in_array($route->parameters['locale'], $languages))
{
$language = $route->parameters['locale'];
session()->put('language', $language);
}
} elseif (config('app.locale')) {
$language = config('app.locale');
}
if (isset($language) && in_array($language, $languages)) {
app()->setLocale($language);
}
return $next($request);
}
}

session not persisting in laravel

I use Session in laravel, but when I get session in controller, it's not work.
web.php
Route::get('locale/{locale}',function ($locale){
//Session::put('locale',$locale);
session(['locale' => $locale]);
Session::save();
return redirect()->back();
});
Localization.php
public function handle($request, Closure $next)
{
if(\Session::has('locale')){
\App::setLocale(\Session::get('locale'));
session(['locale' => \Session::get('locale')]);
\Session::save();
}
return $next($request);
}
Kernel.php
protected $middleware = [
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\Localization::class,
],
'api' => [
\App\Http\Middleware\EventLogMiddle::class,
'throttle:600,1',
'bindings',
],
];
MachCtrl.php (extends Controller)
public function index()
{
$lang = session('locale');
$config = json_encode([
"table" => "Machine_list",
"title" => "machine list",
"rows" => 20,
"column" => [
"Machine_id", "VM_name", "Machine_location","IP_address",
"Network_status", "Current_status"
],
"CUDP" => "0111",
"CreateRoute" => route('machine.create'),
"DeleteRoute" => route('machine.destroy'),
"UpdateRoute" => route('machine.editInfo'),
"locale" => $lang,
]);
return view('table.show')->with(['config' => $config, 'lang' =>
$lang]);
}
I save Session in router and middlemare, it's not work.
But when I put Session in Controller, it's work. As following code:
public function index()
{
session(['locale' => 'en']);
$lang = session('locale');
$config = json_encode([
"table" => "Machine_list",
"title" => "machine list",
"rows" => 20,
"column" => [
"Machine_id", "VM_name", "Machine_location","IP_address",
"Network_status", "Current_status"
],
"CUDP" => "0111",
"CreateRoute" => route('machine.create'),
"DeleteRoute" => route('machine.destroy'),
"UpdateRoute" => route('machine.editInfo'),
"locale" => $lang,
]);
return view('table.show')->with(['config' => $config, 'lang' =>
$lang]);
}
I really want to know what happen in my project.
Thanks.
Edit:
I use dd(session()) in my code:
-web.php
Route::get('locale/{locale}',function ($locale){
Session::put('locale',$locale);
Session::save();
dd(session());
return redirect()->back();
});
Result:
-Localization.php
public function handle($request, Closure $next)
{
if(\Session::has('locale')){
\App::setLocale(\Session::get('locale'));
session(['locale' => \Session::get('locale')]);
//dd(session());
\Session::save();
}
return $next($request);
}
Result:
-MachCtrl.php
public function index()
{
dd(session());
$lang = session('locale');
$config = json_encode([
"table" => "Machine_list",
"title" => "machine list",
"rows" => 20,
"column" => [
"Machine_id", "VM_name", "Machine_location","IP_address",
"Network_status", "Current_status"
],
"CUDP" => "0111",
"CreateRoute" => route('machine.create'),
"DeleteRoute" => route('machine.destroy'),
"UpdateRoute" => route('machine.editInfo'),
"locale" => $lang,
]);
return view('table.show')->with(['config' => $config, 'lang' =>
$lang]);
}
Result:
Try using a different session driver to round down your issue a little bit.
EDIT: Sorry I can't comment yet, <50rep :(
I checked my working code. I set the whole cycle as:
Language middleware:
class Language
{
protected $app;
public function __construct(Application $app, Request $request) {
$this->app = $app;
}
public function handle($request, Closure $next)
{
$this->app->setLocale(session('user_locale', config('app.locale')));
return $next($request);
}
}
In my middleware Kernel.php:
protected $middlewareGroups = [
'web' => [
\Illuminate\Session\Middleware\StartSession::class,
//...
\App\Http\Middleware\Language::class,
]
];
And in route:
Route::get('locale/{locale}',function ($locale){
session(['user_locale' => $locale]);
});

Authentication redirects fail

when I login with wrong credentials I got the right response.
when I login with the right credentials the login page reload with 302 request
but it never redirect to statistics page.
when I debug it I found that the code goes to this authinticate.php in the middleware folder,
it redirect to the guest login state
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
see the code:-
Route.php
Route::get('login', 'LoginController#index');
Route::post('signin', 'LoginController#signin');
Route::get('signout', 'LoginController#signout');
Route::group(['prefix' => 'api'], function() {
Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
Route::post('authenticate', 'AuthenticateController#authenticate');
});
Route::group(['middleware' => ['web']], function () {
Route::auth();
Route::get('/', 'StatisticsController#index');
Route::get('/statistics', 'StatisticsController#statistics');
});
Login Controller
public function index() {
return view('login');
}
public function signin(Request $request) {
$errors = [];
$email=$request['email'];
$password= $request['password'];
$credentials = array('email' => $email, 'password' => $password);
if(Auth::attempt($credentials))
{
return redirect('/statistics');
}
return "bad request";
}
public function signout()
{
Auth::logout();
return redirect('/login'); }
}
Statistics Controller
class StatisticsController extends Controller {
public function __construct()
{
$this->middleware('auth');
}
public function index() {
return view('statistics')->with($data);
}
public function statistics() {
return view('statistics');
}
}
Kernal.php note that there is JWT auth library I use it for restful authentication with the mobile app only.
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'jwt.auth' => 'Tymon\JWTAuth\Middleware\GetUserFromToken',
'jwt.refresh' => 'Tymon\JWTAuth\Middleware\RefreshToken'
];
middleware/authenticate.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Authenticate
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
}
Check your cache.I had a similar problem, where I lost a couple of hours, so these where some of the steps I've made:
php artisan route:clear
clear browser cache
run composer update
Download a fresh copy of laravel(new project), and then slowly merge chunks of your code into the new project
Quick Analysis:
There's no problem with your Authentication method, or your controllers.
The problem lies with the fact that you don't have a route for "/statistics"
And with Laravel at-least starting version 5, you have to be explicit about your routes "PS: they deprecated Route::Controller()"
By the way
Route::get('/', 'StatisticsController#index');
Refers to your application base route
Solution
Add the statistics route
Route::get('/statistics', 'StatisticsController#statistics');
For example.
You are redirecting to StatisticsController#statistics but there is no statistics function defined in your StatisticsController.

Call to a member function set() on null

I am trying to use oauth for google in laravel 5 but i am getting the error. Can any one help me to sort out this problem.
Followings are my files please check out
.env
GOOGLE_ID = 'mygoogleId'
GOOGLE_SECRET = 'mysecretID'
GOOGLE_REDIRECT = http://localhost:8090/users
services.php
'google' => [
'client_id' => env('GOOGLE_ID'),
'client_secret' => env('GOOGLE_SECRET'),
'redirect' => env('GOOGLE_REDIRECT'),
],
AuthController
public function redirectToProvider() {
return Socialite::driver('google')->redirect();
}
public function handleProviderCallback() {
$user = Socialite::driver('google')->user();
console.log($user);
}
routes.php
Route::get('google', 'Auth\AuthController#redirectToProvider');
Route::get('google/callback', 'Auth\AuthController#handleProviderCallback');
//I have set the providers and aliases in app.php.
Here is the code where i am getting an error
//on set() method
public function redirect()
{
$state = str::random(40);
if ($this->usesState()) {
$this->request->getSession()->set('state', $state);
}
return new RedirectResponse($this->getAuthUrl($state));
}
Thanks in advance..
Hey If you are using laravel 5.2, this is worked for me.
Put your controllers in 'web' middleware. like,
Route::group(['middleware' => 'web'], function() {
Route::get('google', 'Auth\AuthController#redirectToProvider');
Route::get('google/callback', 'Auth\AuthController#handleProviderCallback');
});
and Make sure Kernel file has middleware classes registered.
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\Perkweb\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Perkweb\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];

Config oauth2 for dingo/api Laravel 4.2 has an error Argument 1 passed to

I am BeanNguyen.
I am a beginer with Laravel framework. So i want to build a webservice RestAPI (laravel 4.2).
I use https://github.com/dingo/api and oauth2 lucadegasperi/oauth2-server-laravel to protect my api. But when i complete all config files and i use Postman ( https://www.getpostman.com/ ) to send request.
I have a error :
*ErrorException (E_UNKNOWN)
Argument 1 passed to Dingo\Api\Auth\LeagueOAuth2Provider::__construct() must be an instance of League\OAuth2\Server\ResourceServer, instance of LucaDegasperi\OAuth2Server\Authorizer given, called in /home/vagrant/Code/webservice/app/config/packages/dingo/api/config.php on line 110 and defined*
So please help me to fix this problem :). This is my config files:
app\routes.php
Route::api('v1', function () {
Route::group(['prefix' => 'protected', 'protected' => true, 'providers' => 'oauth'], function () {
Route::post('user', function () {
$user = API::user();
return $user;
});
});
Route::group(['prefix' => 'unprotected', 'protected' => false], function () {
});
});
app\config\packages\dingo\api\config.php
'auth' => [
'basic' => function ($app) {
return new Dingo\Api\Auth\BasicProvider($app['auth']);
},
'oauth' => function ($app) {
$provider = new Dingo\Api\Auth\LeagueOAuth2Provider($app['oauth2-server.authorizer'], false);
$provider->setUserCallback(function($id) {
return User::find($id);
});
$provider->setClientCallback(function($id) {
return Client::find($id);
});
return $provider;
}
],
app\config\packages\lucadegasperi\oauth2-server-laravel\oauth2.php
'grant_types' => [
'password' => [
'class' => 'League\OAuth2\Server\Grant\PasswordGrant',
'access_token_ttl' => 604800,
// the code to run in order to verify the user's identity
'callback' => function($username, $password){
$credentials = [
'email' => $username,
'password' => $password,
];
if (Auth::once($credentials)) {
return Auth::user()->id;
} else {
return false;
}
}
],
],
and this is my problem:
ErrorException (E_UNKNOWN)
Argument 1 passed to Dingo\Api\Auth\LeagueOAuth2Provider::__construct() must be an instance of League\OAuth2\Server\ResourceServer, instance of LucaDegasperi\OAuth2Server\Authorizer given, called in /home/vagrant/Code/webservice/app/config/packages/dingo/api/config.php on line 110 and defined
Please help me :), thank you very much :)
My config (app\config\packages\dingo\api\config.php) looks like this which is pretty different than yours. On Laravel 4.2.
'auth' => [
'oauth' => function ($app) {
$provider = new Dingo\Api\Auth\LeagueOAuth2Provider($app['oauth2-server.authorizer']->getChecker());
$provider->setUserResolver(function ($id) {
return User::find($id);
});
$provider->setClientResolver(function ($id) {
return Client::find($id);
});
return $provider;
}
]

Resources