Tymon JWTAUTH exclude routes from token - laravel-5

I installed laravel 5.6 and configured tymon jwtauth token.
All working fine and done.
In laravel 5.1 i used this function to exclude function from jwt authentication:
public function __construct() {
$this->middleware('jwt.auth', ['except' => ['login']]);
}
tried also :
public function __construct() {
$this->middleware('jwt.auth')->except([
'login'
]);
}
It's not working in laravel 5.6, any idea? I want to exclide the login function so the user can login, take the token and send it with each request.

protected $routeMiddleware = [
'jwt.auth' => 'Tymon\JWTAuth\Middleware\GetUserFromToken',
'jwt.refresh' => 'Tymon\JWTAuth\Middleware\RefreshToken',
]
I was putting this in
protected $Middleware
in api.php I put my routes not in web.php
Route::post('user/register', 'APIRegisterController#register');
Route::post('user/login', 'APILoginController#login');
Route::middleware('jwt.auth')->get('testFunc', 'testController#testFunc');

Related

laravel handler always return false when i use spatie middleware

I'm trying to create permissions and roles for users in a Laravel API Project. I'm using Passport and Spatie's Permission package. Using that I added a middleware:
Route
Route::middleware('auth:api')->group(function () {
/** Roles Route */
Route::get('roles',[RoleController::class, 'index'])->middleware('permission:role-list');
}
Handler.php:
public function render($request, Throwable $exception)
{
if ($exception instanceof UnauthorizedException) {
return response()->json(['User does not have the right roles.'],403);
}
return parent::render($request, $exception);
}
Controller:
function __construct()
{
$this->middleware('permission:role-list', ['only' => ['index']]);
$this->middleware('permission:role-create', ['only' => ['store']]);
$this->middleware('permission:role-edit', ['only' => ['update']]);
$this->middleware('permission:role-delete', ['only' => ['destroy']]);
}
public function index()
{
$roles = Role::all();
return response(['role' => $roles], 200);
}
I created an admin account and it was given all the existing permissions, but whenever I ask for the route, it shows me that error message:
User does not have the right roles.
I checked the database and the user had all the required permissions for that.
First of all add the package middlewares in the Kernel.php as described here.
protected $routeMiddleware = [
// ... other middleware
'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
'role_or_permission' => \Spatie\Permission\Middlewares\RoleOrPermissionMiddleware::class,
];
Depending on where you want to define the permissions to access a method either define them in the Controller or on the route. Adding them to both the route and Controller is only doing the same thing.
Changing something in the Handler.php should not be required.
Note that permissions can have different guards. For example it can be web or api.
After changing roles or permissions it sometimes helps to reset the cache. Resetting the cache can be done with php artisan permission:cache-reset command.

Laravel Sanctum SPA Logout Testing

I logout of my application via:
Auth::guard('web')->logout();
Please note, it's the SPA use of Sanctum so no tokens.
Then in my test, I check if the user is logged out via:
Sanctum::actingAs(User::first(), ['*']);
$response = $this->postJson(
route('logout')
); // runs auth logout
$this->assertGuest();
The above fails, yet, when I do not use Sanctum::actingAs(User::first(), ['*']); and instead do a call to my login:
$response = $this->postJson(
route('login'),
[
'email' => User::first()->email,
'password' => 'xyz',
]
);
The test passes.
Am I missing something with Sanctum::actingAs(User::first(), ['*']);, the docs say to use this for testing, does this not work when it's an SPA with cookie based authentication?
Change your logout middleware to web:
Route::middleware('auth:web')->group(function () {
Route::post('/logout', [AuthController::class, 'logout']);
});
Then, in logout():
class AuthController extends Controller
{
/**
* #return JsonResponse
*/
public function logout(): JsonResponse
{
// If with tokens - delete them:
// Auth::user()->tokens()->delete();
Auth::guard('web')->logout();
return response()->json([
'message' => 'Tokens Revoked'
]);
}
}

Auth::user() returns null on Module __construct()

I created a new Module named Article using laravel-modules. Some backend routes needed authentication and i added auth middleware and an additional permission view_backend. I am using https://github.com/spatie/laravel-permission package for role-permissions.
the issue is when i try to access the route admin/article/posts it prompts me the login as expected. But after login it show null on __construct() method for Auth::user();
I added web middleware as mentioned on #204 but it did not solve the issue. Can you please guide me to resolve this? My project is on Laravel 5.6 and using the latest version of Laravel-Modules
Route::group(['namespace' => 'Modules\Article\Http\Controllers\Backend', 'as' => 'backend.article.', 'middleware' => ['web', 'auth', 'can:view_backend'], 'prefix' => 'admin/article'], function () {
Route::resource("posts", "PostsController");
});
My project is hosted at Github, https://github.com/nasirkhan/laravel-starter/tree/module
First of all, add Spatie Middleware to your kernel:
protected $routeMiddleware = [
// ...
'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
];
Then in your controller check for permission or roles:
public function __construct(Request $request)
{
$this->middleware(['permission: order.index']);
}
Now you can access to your authenticated with $request->user() like:
public function create(Request $request)
{
if ($request->user()->hasRole('admin')) {
// return view("carmodel.create", ["manufacturers"=>$manufacturers]);
} else {
return view("admin.error", ['code'=>'001','msg'=>'err']);
}
}
According to the docs:
In previous versions of Laravel, you could access session variables or the authenticated user in your controller's constructor. This was never intended to be an explicit feature of the framework. In Laravel 5.3, you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.
As an alternative, you may define a Closure based middleware directly
in your controller's constructor. Before using this feature, make sure
that your application is running Laravel 5.3.4 or above:
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->projects = Auth::user()->projects;
return $next($request);
});
}
Or you could typehint it:
public function index(Request $request)
{
$projects = $request->user()->projects;
$value = $request->session()->get('key');
}
Docs

Laravel login redirected you too many times

I have been struggling with this from quiet a time now, what i am trying is to redirect all the url's hit by non-logged in users to login page and it gives me this error, which I am sure is because it is creating a loop on /login URL. authentication is checking for authorized user in login page also. however I wish the login page should be an exception when checking the auth. I may be doing something wrong which I am not able to get. here goes my code.
routes.php
Route::post('login', 'Auth\AuthController#login');
Route::get('login' , 'Auth\AuthController#showLoginForm');
Route::get('/' , 'Auth\AuthController#showLoginForm');
kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Auth\Access\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'acl' => \App\Http\Middleware\CheckPermission::class,
];
Authenticate class
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);
}
}
AuthController class
class AuthController extends Controller {
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/dashboard';
protected $loginPath = '/login';
protected $redirectPath = '/dashboard';
public function __construct(){
$this->middleware('auth', ['except' =>'login']);
/* I have been trying these many things to fix this, all in loss.
// $this->middleware('acl'); // To all methods
// $this->middleware('acl', ['only' => ['create', 'update']]);
// $this->middleware('guest', ['only' => ['/login']]);
// echo "Message"; exit;
// $this->middleware('auth');
// $this->middleware('auth', ['only' => ['login']]);
// $this->middleware('auth', ['only' => ['/login']]);
// $this->middleware('auth', ['except' => 'login']);
// $this->middleware('guest');
// $this->middleware('guest', ['only' => ['logout' , 'login', '/login', '/']]);
}
Please help me, It going all above my head, seems some sort of rocket science to me. well btw I am new to laravel and may be doing some silly thing around, apologies for that. Thanks in Advance.
You need add route login outside Laravel group:
routes.php
Route::auth();
Route::group(['middleware' => 'auth'], function () {
// All route your need authenticated
});
Aditionally, you can see yours route list using:
php artisan route:list
Why you are doing all this just to redirect every non-logged in user to login form?
i think you can just do this
Routes.php
Route::post('login', 'Auth\AuthController#login');
Route::get('login' , 'Auth\AuthController#showLoginForm');
Route::get('/' , 'Auth\AuthController#showLoginForm');
Route::group(['middleware' => 'auth'], function () {
// any route here will only be accessible for logged in users
});
and auth controller construct should be like this
AuthController
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
The problem is with your routes.
When I enter and I am not logged out you send me to login(get) route. And as you are specifying the middleware in the construct function in the AuthController, every time a method of the AuthController is called, construct function is called again and sends you back at login.. and it repeats indefinitely.
like #mkmnstr say
The problem is with your routes.
When I enter and I am not logged out you send me to login(get) route. And as you are specifying the middleware in the construct function in the AuthController, every time a method of the AuthController is called, construct function is called again and sends you back at login.. and it repeats indefinitely.
to fix that u should add
Auth::logout();
Here
...
} else {
Auth::logout(); // user must logout before redirect them
return redirect()->guest('login');
}
...
If your working with custom middleware you must follow it's all rules
in my case, I have to define a custom route class in the web middleware group.
In the world of copy-paste sometime we make mistakes.
Middleware :
public function handle($request, Closure $next)
{
if(!isset(session('user'))){
return redirect('login');
}
return $next($request);
}
}
My Mistake in Kernel.php
if custom middleware class present in web $middlewareGroups will check condition 2 times so it will give error as: redirected you too many times
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\webUser::class, //Remove
],
protected $routeMiddleware = [
'webUser'=> \App\Http\Middleware\webUser::class //Keepit
]
I had same problem after creating my own route service provider. The problem was that when I tried to login, in first time login page showed and after entering credentials I encountered "redirected too many times" and redirected to my admin dashboard and login route!
the solution was: adding middleware "web" into my routes:
Route::middleware('web')->group(base_path('Admin/routes.php'));

Laravel authentication for register

laravel authentication model
Is there any possible to make /register only you logged
How to make it with : (Auth::check()) ??
By default in construct of \app\Http\Controllers\Auth\AuthController.php we have middleware guest for all except logout:
public function __construct()
{
$this->middleware('guest', ['except' => [
'logout',
]
]);
}
Middleware guest link for:
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
And use handle method:
public function handle($request, Closure $next)
{
if ($this->auth->check())
{
return new RedirectResponse(url('/'));
}
return $next($request);
}
It's mean that everybody who try access all Auth method except logout will be redirected to main page.
You should look at middleware if your are at laravel 5: https://laravel.com/docs/master/middleware
And filters for laravel 4: https://laravel.com/docs/4.2/routing

Resources