Laravel 5 Redirecting to login page after authentication instead of Dashboard - laravel-5.1

I have this problem, my application should redirect users to admin area whose routes are protected (have middle auth). When I login it redirects to login page again but when place the dashboard route outside the route group, it behaves well. What may be the problem? This is my code:
Code for protected route (does not work) after login
Route::group(['middleware'=>'auth'], function(){
Route::get('backend/dashboard', array('as'=>'dashboard', 'uses'=>'BackendDashboardController#getDashboard'));
});
Code for dashboard route placed outside the route group (Works well after login)
Route::get('backend/dashboard', array('as'=>'dashboard', 'uses'=>'BackendDashboardController#getDashboard'));
Auth controller - Post login function
protected function postLogin() {
$request = Input::all();
$user = array(
'email' => $request['email'],
'password' => $request['password']
);
if ($this->auth->attempt($user)) {
return redirect(route('dashboard'));
}else{
return redirect(route('login'));
}
}
I really want to protect my admin routes and place all of them under auth middleware. Kindly avice

It only redirects, if you are not authorize/loggedin, otherwise it works fine.
and I think you are missing something in Route::group() you also need to mention the prefix eg
Route::group(['prefix'=>'backend', 'middleware'=>'auth'], function(){
Route::get('dashboard', array('as'=>'dashboard', 'uses'=>'BackendDashboardController#getDashboard'));
});
Edited
Also try to update your attempt method, then try it, eg:
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return redirect()->intended('dashboard');
}

Related

ASP.NET MVC 6 Change Default Url Redirect When Not Logged In

I have a mvc project in developemnt, when a user isn't logged in and trys to go to a page that ISN'T the login or register (AllowAnonymous) they're automatcally redirected to ~/Account/Login?ReturnUrl=%2F"PageTryingToAccess".This is done via a authorization needed statement on the Program.cs.
My login page is the ~/home/(index), the default page on the (portal) website. Is there a way of overiding the ~/Account/Login default? I can not find where this is declared in the solution!
Is there a way of overiding the ~/Account/Login default?
In .net6, you can add below code in Program.cs:
builder.Services.ConfigureApplicationCookie(opts =>
{
opts.LoginPath = "/Home/Index";
});
In asp.net core3, you can use below:
services.ConfigureApplicationCookie(opts =>
{
opts.LoginPath = "/Home/Index";
});
Result:

Same Url but different controller after logged in to the application

I want to make simple application using laravel5.2 in which there will come sign in form on base url when i log in to the application there need to give a different view i.e. Client dashboard at same url. How can i do that Please help me. Thanks In Advance !
You could do something like this for root / URL:
Route::get('/', function(){
if (!Auth::check()) {
return View::make('login'); // login view if not authenticated
// or call controller for login
}
else{
return View::make('dashboard'); // dashboard view if authenticated
// or call controller for dashboard
}
});
This is very simple. You have to just make a function in WelcomeController or in other controller. And do check if user is already login or not and redirect to proper view page accordingly.
For example :
In your routes.php file write route like this
$router->get('/',array(
'as' => 'home',
'uses' => 'WelcomeController#welcome'
));
And in your controller ,in case of this example : WelcomeController make a function named welcome and do some auth check like this
public function welcome()
{
if(Auth::check()){
//get some data for user dashboard
return view('dashboard');
}
return view('login');
}
PS: for good practice, use dependency injection. In this case inject Guard
class instead of using Auth facade.

Create a general rule for urls in Laravel

I want to redirect users back to the login page if they attempt to access certain pages on my site. I want to create a general rule so that I do not have to implement it on every page for every url separately.
For example if user try to access /profile , I want them to redirect back to login page if they are not logged in. I tried doing this using group routes by putting an if condition but that did not work. Moreover I am not an expert in laravel. This is what I tried.
Route::group(['prefix' => '/users'], function () {
if(Auth::user()){
Route::get('/','FacebookControllers\FacebookPagesController#listUsers');
Route::get('{id}/profile', 'FacebookControllers\FacebookPagesController#userProfile');
}
else {
return redirect('/');
}
});
Check out laravel's Auth middleware.
Documentation here: laravel.com/docs/5.1/routing#route-groups
Example (taken from the docs):
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
// Uses Auth Middleware
});
Route::get('user/profile', function () {
// Uses Auth Middleware
});
});

URL encoding # sharp to Durandal SPA

I know it is not necessary to specify a login URL to a Durandal login page. But I wonder how to fix the following problem I'm facing to redirect a Authentication to a specific Durandal Page that has a Sharp sign (i.e. #).
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
//LoginPath = new PathString("/" + HttpUtility.UrlDecode("#") + "/login")
LoginPath = new PathString("/#/login")
});
...
}
When I paste:
http://localhost/#/login
to a browser URL I can navigate to the login page without any problems. I can login and it is working fine.
Because I'm mixing MVC with SPA in some scenarios, when I add [Authorize] attribute to an MVC controller, then I will be redirected as expected to
http://localhost/%23/login?ReturnUrl=%2Fe
and I get the error:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /#/login
how to use the # sign instead of %23 char encoding? or maybe I'm messing something else!!!
FYI:
My question is related to character encoding not something line this: Login page on different domain because I may face the same problem in other situations in the future.
As far as I know it isn't possible to use a # from the server. A possible solution could be to redirect the user from the shell in durandal.js when the user isn't authenticated.
I don't know if it is too late in the life cycle but you could try to catch the redirect in the global asax file in the Application_EndRequest event and fix the response. I have code like this to change the actionresult to a jsonresult that my js can work with so that when a user attempts to reach an MVC controller resource that I have protected via java script ajax I can handle it properly.
protected void Application_EndRequest()
{
var context = new HttpContextWrapper(this.Context);
// If we're an ajax request and forms authentication caused a 302,
// then we actually need to do a 401
if (FormsAuthentication.IsEnabled && context.Response.StatusCode == 302
&& context.Request.IsAjaxRequest())
{
var jsRet = new JSONFunctionResult<Boolean>();
if (this.Request.IsAuthenticated)
{
jsRet.Messages.Add(new JSONFunctionResultMessage()
{
Text = string.Format("You must have one of these roles to perform the operation: {0}", context.Response.Headers["RolesRequired"]),
Title = "Security Violation",
Type = (int)JSONFunctionResultMessageTypes.authorization
});
}
else
{
jsRet.Messages.Add(new JSONFunctionResultMessage()
{
Text = "You must be logged into to access this resource",
Title = "Security Violation",
Type = (int)JSONFunctionResultMessageTypes.authentication
});
}
jsRet.OperationStatus = JSONFunctionResultOperationStatus.error.ToString();
string jresponse = JsonConvert.SerializeObject(jsRet);
context.Response.Clear();
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
context.Response.Write(jresponse);
}
}
In my code I check for a redirect and if forms auth is enabled and if the user is Authenticated and change the response accordingly. For your code you could maybe change the response to go to your correct login page?

ZfcUser Redirect Roles to different Pages after Login

I'm using the ZfcUser and BjyAuthorize in my Project. If a user logged in, he will be redirected to my default route.
But i want to change it, so if a User with role A will redirected to Page A and user with role B will redirected to page B.
Any idea, how to realize this?
I have actually done this and created the merge request in GitHub. It's actually a very small change that needs to be done in zfc-user/src/ZfcUser/Controlelr/UserController.php. Within authenticateAction() you need to replace this:
return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
For this:
$route = $this->getOptions()->getLoginRedirectRoute();
if(is_callable($route)) {
$route = $route($this->zfcUserAuthentication()->getIdentity());
}
return $this->redirect()->toRoute($route);
And in your config/autoload/module.zfcuser.global.php file you'll be able to use a callback for the login_redirect_route:
'login_redirect_route' => function(\ZfcUser\Entity\UserInterface $user) {
if($user->getUsername()=='Admin') {
return 'admin';
}
return 'user';
}
As I have to check several things depending on the role I've create a simple module than once the users is logged (default route after loggin) and depending on the role (avaliable through bjyautorize) redirects the application to the correc url.
Maybe it's not an elegant way but you don't have to modify zfcUser code.
You can setup redirect after login in config file.
'login_redirect_route' => '/your-url',
your-url accessible from all type of user and then create switch case to match your role and redirect page to role specific page.
$roles = $this->serviceLocator->get('BjyAuthorize\Provider\Identity\ProviderInterface')->getIdentityRoles();
switch ($roles){
case "admin":
$this->redirect()->toRoute('user_admin');
case "user":
$this->redirect()->toUri('user.html');
}
Suppose you have an 'admin' role in bjyauthorize that you want to redirect to another route.
In your loginAction replace the code:
if ($this->zfcUserAuthentication()->getAuthService()->hasIdentity()) {
return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
}
with this code:
if ($this->zfcUserAuthentication()->getAuthService()->hasIdentity()) {
$roles = $this->serviceLocator->get('BjyAuthorize\Provider\Identity\ProviderInterface')->getIdentityRoles();
if (in_array('admin',$roles))
{
return $this->redirect()->toRoute('admin_route');
} else {
return $this->redirect()->toRoute('user_route');
}
}

Resources