Authentication redirects fail - laravel

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.

Related

How can I force Authenticate.php middleware respond with a json object not return redirect if I use an API? I have JWT login

{
public function handle($request, Closure $next)
{
if (! $request->expectsJson()) {
abort(response()->json([
'success' => false,
'data' => 'Unauthorize'
]));
}
return $next($request);
}
}
I tried this but doesn't matter whether the condition is true, it nevershows me data i should / souldn't be able to see (doesn't matter that I provide a token or no).
This is how I call it in controller
public function __construct()
{
$this->middleware('auth:api');
}
api.php
Route::group([
'middleware' => 'api',
], function ($router) {`
Route::post('login', [\App\Http\Controllers\AuthController::class, 'login']);
Route::post('register', [\App\Http\Controllers\AuthController::class, 'register']);
});
in app/Exceptions/Handler.php add this
use Illuminate\Auth\AuthenticationException;
protected function unauthenticated($request, AuthenticationException $exception)
{
return $request->expectsJson()
? response([
'success' => false,
'data' => 'Unauthorize'
])
: redirect('/login');
}
NOTE:_ it will work if you add header Accept:application/json

Trying to get property 'headers' of non-object in __construct() laravel 6.18.13

I need to check whether a controller function is called from internal views or from apis so I did
public function __construct()
{
$this->middleware(function ($request, $next) {
if (Auth::user()) {
return 'auth';
}
else {
return 'client';
}
});
}
but it gives me this error Trying to get property 'headers' of non-object in __construct()
and my middleware route looks like
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::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,
'client' => CheckClientCredentials::class,
];
The CheckClientCredentials class is as follows
<?php
namespace Laravel\Passport\Http\Middleware;
use Illuminate\Auth\AuthenticationException;
use Laravel\Passport\Exceptions\MissingScopeException;
class CheckClientCredentials extends CheckCredentials
{
protected function validateCredentials($token)
{
if (! $token) {
throw new AuthenticationException;
}
}
protected function validateScopes($token, $scopes)
{
if (in_array('*', $token->scopes)) {
return;
}
foreach ($scopes as $scope) {
if ($token->cant($scope)) {
throw new MissingScopeException($scope);
}
}
}
}
I am new to laravel please enlighten me.
The middleware should return: redirect('route/url') or proceed further (return $next($request))
$this->middleware(function ($request, $next) {
//if user is authenticated via api passport
if (auth('api')->user()) {
$this->middleware('auth:api');
}
//if user is authenticated via web
else if(auth()->user()) {
$this->middleware('auth');
}
// when user is not authenticated
else {
return redirect('/login');
}
return $next($request);
});

Laravel implementing simple MiddleWare doesn't work

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.

Laravel 5.2 JSON response to request with wrong api_token

I use auth:api middleware in controller (Laravel 5.2).
class RestfulController extends Controller
{
public function __construct() {
$this->middleware(['api', 'auth:api'], ['except' => ['login'] ]);
}
}
routes:
Route::group(['prefix' => 'api'], function () {
Route::get('/login', ['uses' => 'RestfulController#login', 'as'=>'login']);
Route::get('/list', ['uses' => 'RestfulController#list', 'as'=>'list']);
});
If request doesn't contain or contains invalid api_token framework redirects to login page. Instead I would like to return JSON response with error. How it can be implemented?
change app/Http/Middleware/Authenticate.php handle method,it will response json
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
$response = [
'status' => 'error',
'message' => 'This is error message'
];
return Response::json($response);
}
}
return $next($request);
}
You should check api and auth:api middleware group and look for witch one is doing it. If it's inside a vendor package, you'll need to extend it and make your changes.

Laravel 5.1 Authentication views

I'm using laravel 5.1 and the modular package.
In my controller I use the following login method:
public function postLogin(Request $request)
{
$email = $request->input('email');
$password = $request->input('password');
if (Auth::attempt(['email' => $email, 'password' => $password])) {
return redirect()->intended('admin/dashboard');
}
return redirect('/login')->withErrors([
'email' => 'These credentials do not match our records.']);
}
My route:
Route::group(array('module' => 'Admin', 'namespace' => 'App\Modules\Admin\Controllers'), function() {
Route::get('admin/dashboard', [
'middleware' => 'auth',
'uses' => 'AdminController#index'
]);
}}
My controller:
public function index()
{
return view("Admin::index");
}
My Middleware/Authenticate:
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('auth/login');
}
}
return $next($request);
}
This works and redirects me to the index view after login.
When the user is not logged in, it is still possible to access the index view by accessing the url: localhost/admin/dashboard.
How can I redirect the user to a custom page which shows an error to the user that it is not possible to access the url localhost/admin/dashboard when he is not logged in?
Any ideas? Thank you
The issue is with your route the middleware should be at the top level as soon as you hit the controller it should redirect if not authenticated
Route::group(['middleware'=>'auth','module' => 'Admin', 'namespace' => 'App\Modules\Admin\Controllers'], function()
{
Route::get('admin/dashboard', ['uses' => 'AdminController#index']);
});
secondly if you want to redirect user to a custom page you can do this
public function redirectUnAuthenticateUser()
{
\Session::flash('login_error', 'Kindly login before you can access this page');
//create a view that user would be redirected to
return view('session.unauthenticated') ;
}
and the change your auth function to below
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->route('you-custom-rout-name-matching-above-function');
}
}
return $next($request);
}
and on your view you can get the value of the flash message

Resources