How to redirect to login page if AbpAuthorize is failed in asp.net mvc? - asp.net-mvc

I have modified the asp.net boilerplate mvc template css, but somehow, I might mess up with the code. Now if the user is not logged in/not authorized, the error pops out, click ok, instead of redirecting to the login page, it redirects to the default $urlRouterProvider in the app.js. Here is part of the app config:
app.config([
'$stateProvider', '$urlRouterProvider', '$locationProvider', '$qProvider',
function ($stateProvider, $urlRouterProvider, $locationProvider, $qProvider) {
$locationProvider.hashPrefix('');
$urlRouterProvider.otherwise("/");
$qProvider.errorOnUnhandledRejections(false);
$stateProvider
.state('login', {
url: '/Account/Login',
templateUrl:'/Views/Account/Login.cshtml'
})
.state('dashboard', {
url: '/',
templateUrl: '/App/Main/views/dashboard/dashboard.html',
data: { pageTitle: '' }
})
]);
Can any one please explain what happens behind the scenes? What is the magic code that redirects the user to the login page regardless of what you defined in the angularjs?
Thanks in advance!

After days of search, I found out the reason why it did not work is because the response is not handled by HandleUnauthorizedRequest method. It is supposed to redirect to the path you defined in the startup when receiving 401 unauthorized status.
And why it did not trigger the HandleUnauthorizedRequest is because I removed the AbpMvcAuthorize in Home controller.

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:

Partial View Link on MVC LoginPage not working (User not logged-in/Authorized yet)

I am working on a website in ASP.NET MVC and working on LoginPage. On the LoginPage, we also have 'Forgot Password' link and clicking that link opens a Modal-popup (bootstrap) with content being returned as PartialView.
Problem I am facing is, when I click on 'Forgot Password' link on the page, Index method of Login controller gets called instead of ForgotPassword related method which results in LoginPage being returned in modal popup.
[AllowAnonymous]
[System.Web.Services.WebMethod()]
public ActionResult ForgotPassword()
{
return PartialView("_ForgotPassword");
}
It seems like some sort of authentication issue because if I login using our old Login Page (it's an .aspx page) and then try to manually go to a new ASP.NET MVC page, all the link with partialView on login Page works fine.
Anyone else had this issue? any pointer would be appreciated.
Thanks
Edit 1: Javascript used to call modal popup
function AttachPopup() {
$('.modal-popup').click(function (event) {
event.preventDefault();
event.stopImmediatePropagation();
var url = $(this).attr('data-content-url');
var modalId = $(this).attr('data-target-model');
var target = $(this).attr('data-target-content');
$.ajax({
url: url,
type: 'POST',
datatype: "json",
cache: false,
traditional: true,
success: function (data) {
$(target).empty();
$(target).append(data);
$(modalId).modal('show');
}
});
});
}
url comes correct but still index is called.
When the AllowAnonymous attribute, the onAuthorization method of AuthorizeAttribute simply ignores authorization and authentication checking. Even if you had a global authorization filter. It should still work. A user had a similar issue. Please check out this link
As mentioned, I was converting an aspx website to MVC. In Web.config, we had
<authorization>
<deny users="?" />
</authorization>
This was taking precedence over MVC [AllowAnonymous] attribute. Commenting out above code, fixed my problem.
Word of caution: When you do that, do check that your website is secure with [Authorize] attribute

Laravel 5 Redirecting to login page after authentication instead of Dashboard

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');
}

Grails/JQuery mobile view not displayed after login

Using Grails 2.4.3 and Spring Security plugin :spring-security-core:2.0-RC4
The default login view auth.gsp is working fine.
Added a user and can login, logout
and view secured pages.
Then I added JQuery mobile files to my layout and view.
I copied auth.gsp to /views/login/auth.gsp pastebin
My /views/layouts/main.gsp layout looks like this pastebin
My login page looks like this:
When I login with invalid credentials I get a blank page.
The source of the page before and after submit is exactly the same. pastebin
If I remove <script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.js"></script>
from main.gsp then I do see the output after submit.
Hope someone knows what I'm doing wrong.
UPDATE
In plugin/springsecurity/LoginController.groovy there is
def authfail() {
// ....
if (springSecurityService.isAjax(request)) {
render([error: msg] as JSON)
}
else {
flash.message = msg
redirect action: 'auth', params: params
}
}
If I change this to:
def authfail() {
// ...
flash.message = msg
redirect action: 'auth', params: params
}
then it is working and I see the login view again.
What still does not work is the redirection after successful login. Stil see a blank page.
Found that the answer on Spring Security Refresh Error in Grails jQuery Mobile app solves mine as well
Need to add data-ajax="false" and then it works.

MVC - Identify Page Form Authentication time out

we are developing MVC3 application such that most of our action methods are called via ajax calls and return partialviews. we come across a situation where we need to identify if the action method is called from Form Authentication time out.
public ActionResult LogOn()
{
// I want to return View("LogOn"); if the call is coming from
// Form Authentication time out
return PartialView(Model);
}
here is my web.config looks like:
<authentication mode="Forms">
<forms loginUrl="~/Home/LogOn" timeout="20" />
</authentication>
Appreciate your input.
Your action will never be hit if the authentication cookie has timed out. The forms authentication module directly redirects to the logon page. One possibility for you to detect this happening from client scripting is to set a custom HTTP header in the controller action serving this logon page:
public ActionResult LogOn()
{
var model = ...
Response.AppendHeader("X-LOGON", "true");
return View(model);
}
and then when performing your AJAX request you could use the getResponseHeader method on the XHR object in order to verify if the X-LOGON header was set meaning that the server redirected to the logon page. In this case in your success AJAX handler instead of simply injecting the server response into the DOM or relying on the returned JSON you could show some alert message informing the user that his authentication session has timed out and he needs to login again. Another possibility is to automatically redirect him to the logon page using the window.location.href method:
$.ajax({
url: '/home/some_protected_action',
success: function (data, textStatus, XMLHttpRequest) {
if (XMLHttpRequest.getResponseHeader('X-LOGON') === 'true') {
// the LogOn page was displayed as a result of this request
// probably timeout => act accordingly
}
}
});
There is no way from the server to distinguish between the user loading the page normally versus performing a page refresh.
There are ways to tell the difference between a regular request and an AJAX request, but it doesn't sound like that's what you're asking for.
There is no easy way but if you apply Post-Redirect-Get, I am not sure you will have that problem.

Resources