I'm looking to create a route group that enables particular users to view information on my site without being authenticated.
At the moment, i've created a route service provider called 'public' as follows:
Route::get('customer/application', function () {
return view('customerview.customer-application');
});
When I write 'php artisan route:list' the following comes up for the route:
Method: GET | HEAD
URL: customer/application
Middleware: ''
I have removed all middleware in an attempt to bypass auth, but with no luck.
The area which is redirecting me to the login page is here in App\Exceptions\Handler.php:
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest('login');
}
I also tried assigning the route to 'guest' group but no help. How can I bypass the return redirect()->guest('login'); for different groups?
Rookie mistake - I had a route with customer/{id} so I changed my new route to open/customer/application instead.
But for anyone wondering how to make a route outside of the scope of auth?
In RouteServiceProvider.php I created a mapping for the 'public' routes to enable me to create a new file with all my routes as so:
protected function mapPublicRoutes()
{
Route::group([
'namespace' => $this->namespace,
], function ($router) {
require base_path('routes/public.php');
});
}
In routes/public.php i added the following:
Route::get('open/customer/application', function () {
return view('customerview.customer-application');
});
Route::auth(); is still in my web.php file at the end without any problems / collision.
I hope my mistake will educate others to check their route files before bothering the Stackexchage community :')
Related
What I'm trying to test is to access some routes but these routes are in laratrust role middleware this role is the auth user must be super admin to go in this routes my problem is I don't know how to write this function.
I tried to make the user super admin in the test function like this
public function Test()
{
$user = factory(User::class)->create();
$user->attachRole('superadministrator');
$this->actingAs($user, 'api');
$response = $this->json('GET', 'api/users');
$response->assertStatus(200);
}
but it didn't work even I checked the data base this user is superadministrator and the test give like I'm not super admin
This is my api routes:
Route::group(['middleware' => ['auth:api', 'role:superadministrator']],
function()
{
Route::apiResource('users', 'UserController');
}
This is my index function in UserController:
public function index()
{
return Response()->json(User::all, 200);
}
What I'm expect is a function can access this route because there is more routes in this group and the rest of the tests depends on this function
I've never used Laratrust, but after a quick look at its source code, it looks like the issue is that you need to specify the api guard on your role middleware check. Add ,guard:api to your role middleware:
Route::group(['middleware' => ['auth:api', 'role:superadministrator,guard:api']], function() {
Route::apiResource('users', 'UserController');
}
In the role middleware check, if you don't specify the guard, it will use the default guard defined in your auth config (which is web if you haven't changed it). So, the middleware will be looking for the user from the web auth guard, which doesn't exist.
The good news is, your test worked! It found a bug in your route definition.
I'm new to Laravel 5.6 and are trying to write an API with the public route /signup.
For JWT auth, I'm using jwt-auth 1.0.0-rc.2.
routes/api.php
// This code WORKS, the route is public
Route::middleware('guest:api')->get('/signup', function(Request $request) {
return "Sign up"; // This code belongs in the controller
});
// This code DOES NOT WORK, authentification needed
Route::get('signup', 'AuthController#signup')->middleware('guest');
// This code DOES NOT WORK
Route::group([
'middleware' => 'guest:api'
], function($router) {
Route::get('signup', 'AuthController#signup');
});
I couldn't find anything useful in the docs, but it should be my wrong way of adding the guest permission, as the first example works.
How can I make the the not working code work? Any idea? Thanks!
Route::middleware(['guest:api'])->group(function () {
Route::get('signup', 'AuthController#signup');
Route::get('mySecondRoute', 'AuthController#mySecondFunction');
});
or even just
Route::get('signup', 'AuthController#signup');
out of any group
I use Laravel 5.3 and I have the following problem.
[UPDATE]
My initial trouble was the appearance of an error when performing actions on the site when the user was not logged in the system.
This happened when the browser is started, where cached information is displayed by default on the page. Site interface displayed for logged users, and in his system was not. At the same time, producing some action, I get an error that the user is not authorized.
I also have group auth middleware for all my routes. When I reboot page of the site, the middleware is activated and redirectedme to the login page. The main problem is the browser shows the cached information.
So, in addition to middleware for routes I decided to make auth check in controllers.
[/UPDATE]
I want to check user's auth in every controller's action. Making the auth check in every controllers' action manually isn't a solution, because there are many controllers and actions.
So I decided to make it globally.
As all controllers extends Main Controller (App\Http\Controllers\Controller.php), I decided write the
auth()->check() in constructor:
function __construct()
{
if(auth()->check()) dd('success');
}
But... nothing happened((( Then I found the callAction method in BaseController which Main Controller extends and made checking here:
public function callAction($method, $parameters)
{
if(auth()->check()) dd('success');
return call_user_func_array([$this, $method], $parameters);
}
This time everything's OK, but I don't like this solution, because editing the core files isn't good.
Finally, I redeclared callAction method in Main Controller with auth checking, but I don't like this way too.
Is any solution?
You should use middleware:
Route::get('profile', ['middleware' => 'auth', 'uses' => 'UserController#showProfile']);
Or:
Route::get('profile', 'UserController#show')->middleware('auth');
Or using middleware groups:
Route::group(['middleware' => ['auth']], function () {
// Controllers here.
});
Or using controller's construct:
public function __construct()
{
$this->middleware('auth');
}
You can use auth middleware in your controller
public function __construct()
{
$this->middleware('auth');
}
check here : https://laravel.com/docs/5.3/authentication
if there is a group of routes this would be the easiest way
Route::group(['middleware' => ['auth']], function()
{
// here all of the routes that requires auth to be checked like this
Route::resource('user','UsersController');
}
another ways
function __construct()
{
$this->middleware('auth');
}
another way is specified on controller routes
Route::get('profile', [
'middleware' => 'auth',
'uses' => 'UserController#showProfile'
]);
see documentation
https://laravel.com/docs/5.0/controllers#controller-middleware
I just want to override the postRegister() method to avoid Laravel to login the user automatically after registration. So I did inside the AuthController.php:
public function postRegister(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
$this->create($request->all());
return redirect('test');
}
Laravel create the user without Login like I want, the problem is in the redirect line. For some very strange reason the always redirect the user to the '/auth/login' route.
I commented all my middlewares just to make sure that is not some middleware doing the redirect:
protected $routeMiddleware = [
'auth' => \CapTable\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \CapTable\Http\Middleware\RedirectIfAuthenticated::class,
'activated' => \CapTable\Http\Middleware\UserActive::class,
];
I tried php artisan clear-compiled and php artisan cache:clear and php artisan clear:config to clean all possible cache or config files but Laravel still doing the redirect to /auth/login.
After some debug in the code I saw that its reading my new function who overrides the original in vendor.
I really without ideas, someone here had some similar issue or know how can I find out whats is going on here ?
P.S. test is just a alias to the route that I want to redirect the user.
Thanks Guys
Try giving the exact route as defined in your route.php
public function postRegister(Request $request) {
// your code here
return redirect('/login'); //This is the actual route as defined and not an alias
}
If not, try using return Redirect::to('http://example.com/login'); or return Redirect::back();
The problem wasn't in the backend. I had some redirection in my frontend (Angular.js) that was overriding the Laravel redirection.
window.location = '/auth/login';
But I learned a important lesson: Always check the frontend.
I am brand new to laravel and am setting up admin panel authorization on my first application. The way I have my files setup currently setup is:
controllers/
admin/
dashboard.php
settings.php
non-admin-controller1.php
non-admin-controller1.php
views/
admin/
dashboard.blade.php
login.blade.php
template.blade.php
non-admin-view1.php
non-admin-view1.php
non-admin-view1.php
...and these are my routes
Route::get('admin/login', function()
{
return View::make('admin.login');
});
Route::get('admin/logout', function()
{
return Auth::logout();
return Redirect::to('admin/login');
});
Route::post('admin/login', function()
{
$userdata = array('username' => Input::get('username'),
'password' => Input::get('password'));
if (Auth::attempt($userdata))
{
return Redirect::to('admin');
}
else
{
return Redirect::to('admin/login')->with('login_errors',true);
}
});
Route::controller('admin.dashboard');
Route::get('admin', array('before' => 'auth', function() {
return Redirect::to_action('admin#dashboard');
}));
Route::filter('auth', function()
{
if (Auth::guest()) return Redirect::to('admin/login');
});
When I go to /admin I am redirected to admin/login and asked to login which is exactly how I need it to work. Upon logging in I am redirected to admin/dashboard and it all looks good there too. I am having 2 problems however.
When I go to admin/logout I am logged out but greeted with a blank page (it's not redirecting to admin/login)
When logged out, if I go to admin/dashboard I am greeted with the error
Error rendering view: [admin.dashboard]
Trying to get property of non-object
What am I doing wrong here? What am I doing right? Would it make more sense to create a separate bundle for admin? Thanks!
So I was able to solve my problem a slightly different way. I created an (base) Admin_Controller in the root of the controllers folder, with a constructor calling the auth filter before execution:
class Admin_Controller extends Base_Controller {
public function __construct()
{
$this->filter('before', 'auth');
}
}
and then made all my admin related controllers in /controllers/admin extend Admin_Controller and call the parent constructor:
class Admin_Dashboard_Controller extends Admin_Controller {
public function __construct()
{
parent::__construct();
}
public function action_index()
{
return View::make('admin.dashboard');
}
}
This might not be the most eloquent solution, but it does the job!
In your admin/login route you have an unnecessary return before the Auth::logout() call, nuke that and it should fix it up.
Another issue here is that only your one 'admin' route is getting filtered. You could wrap all of your admin routes with a Route::group() and apply the 'auth' before filter or you could use Route::filter('pattern: admin/*', 'auth') too.
Check out:
http://laravel.com/docs/routing#filters
For the second issue, is your Admin Dashboard controller class named Admin_Dashboard_Controller and if so, do you have an action_index() or get_index() function in there returning a view?
Check out:
http://laravel.com/docs/controllers#nested-controllers
(I'm assuming you're using L3 here btw.)
For future readers, a very clean way to handle this is using Laravel's Route Groups:
Route groups allow you to share route attributes, such as middleware or namespaces, across a large number of routes without needing to define those attributes on each individual route.
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
// Uses Auth Middleware
});
Route::get('user/profile', function () {
// Uses Auth Middleware
});
});
They can be used not only for authentication, but also Namespaces, Sub-Domains, and more.