How can I redirect users, who or not logged in to login page, in C# MVC 4.5 if they try to access other site pages via URL - asp.net-mvc-4

I have one website, where I want users to be redirected to "Login" page if they are not signed in. The users may try to access the webpages by posting url. I want to do it in C# MVC 4.5
Here I dont want the action "[Authorize]" to be available unless signed in.
It is index action to view index page.
//Login Controller
[AllowAnonymous]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(FormCollection frm)
{
....//other code
}
[Authorize]
public ActionResult Index()
{
List<DTO> obj = objConfigurator.GetDataList();
return View(obj);
}
public ActionResult Edit(int Id)
{
DTO obj = objC.GetListById(Id);
return View(obj);
}

Use the [Authorize] attribute on your controller.
[Authorize]
public class YourController: Controller
{
. . .
[AllowAnonymous]
public ActionResult Register()
{
}
[AllowAnonymous]
public ActionResult LogIn()
{
}
. . .
}
Also, you have to add your login page in the web.config -
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Login" timeout="2880" />
</authentication>
</system.web>
You have another, even better option, to register AuthorizeAttribute as global filter in the global.asax file.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
....
filters.Add(new System.Web.Mvc.AuthorizeAttribute());
}
This way, you only have to apply the [AllowAnonymous] to actions tha you want to be visited by anonimous users.

Related

Asp.net Core 3.1 controller methods with parameters from body is not working

I have WebAPI that working under IIS reverce proxy. WepAPI working as windows service.
Controller:
[HttpPost]
[Consumes(MediaTypeNames.Application.Json)]
[Route("version-post-body")]
public IActionResult VersionPost([FromBody] Test test)
{
return Ok(test.TestString);
}
public class Test
{
[JsonPropertyName("test")]
public string TestString { get; set; }
}
IIS Rewrite
<rule name="MyRewrite">
<match url="api/v2/(.*)" />
<action type="Rewrite" url="http://localhost:10126/{R:1}" />
</rule>
When I send request, i get 408 HTTP Code. But if controller method does't expect parameters from body, it's working fine.
/// WOrk
[HttpPost]
[Route("post-body-without-body")]
public IActionResult Post()
{
return Ok("test");
}
/// not work
[HttpPost]
[Route("post-body")]
public IActionResult Post([FromBody] List<string> test)
{
return Ok(string.Join(";", test));
}
What could be the problem?

How to prevent browser back button after logout Aspnet Core

I have an aspnet core web site, with cookie authentication.
When I logoff, and then, when I click in the back button of the browser, I navigate to the last web page, and I don´t want that, I wan´t the user to be redirect to the login page to be authenticate again.
My startup.cs
public void ConfigureServices(IServiceCollection services)
{
....
services.AddIdentity<ApplicationUser, ApplicationRole>(
config =>
{
config.User.RequireUniqueEmail = true;
config.SignIn.RequireConfirmedEmail = true;
config.Password.RequiredLength = 8;
config.Cookies.ApplicationCookie.LoginPath = "/Home/Login";
})
.AddEntityFrameworkStores<DbContext>()
.AddDefaultTokenProviders();
......
}
My controller.cs
public class HomeController : Controller
{
.....
private readonly string _externalCookieScheme;
....
public HomeController(
.....
IOptions<IdentityCookieOptions> identityCookieOptions,
.....)
{
....
_externalCookieScheme = identityCookieOptions.Value.ExternalCookieAuthenticationScheme;
....
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> Login()
{
// Clear the existing external cookie to ensure a clean login process
await HttpContext.Authentication.SignOutAsync(_externalCookieScheme);
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LogOff()
{
await HttpContext.Authentication.SignOutAsync(_externalCookieScheme); //don´t remove the cookie
_logger.LogInformation(4, "User logged out.");
return RedirectToAction(nameof(HomeController.Login), "Home");
}
}
What I am missing here?
Best regards.
jolynice
You need to set the Cache-Control header. For a single page or controller, you can set the header like this:
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
If that doesn't work, make sure the header is not being overwritten. You can find a detailed explanation in my blog post: How To Prevent the Back Button after Logout in ASP.NET Core MVC.
Make sure that in your Logout action method , you are calling HttpContext.SignoutAsync() method ( using correct overload). After this if you press back button, you will be redirected to login

Default Login Location is not overridden in ASP.NET 5 MVC6

I have the following HomeController
[Area("Admin")]
[Authorize(Roles = "Admin")]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
I have moved the Account section to its own area called Admin.
In ASP.NET 4 to change the default login location, one would change the web.config.
However in ASP.NET 5 I understand you have to do this in the Startup.cs as indicated in this answer
At the bottom of my Startup.cs
public void ConfigureServices(IServiceCollection services){
...
services.Configure<CookieAuthenticationOptions>(options =>
{
options.LoginPath = new PathString("/Admin/Account/Login");
});
However when run my Application /Home/Index it redirect to
http://localhost:59693/Account/Login?ReturnUrl=%2F
and not like the Admin Area like I explicitly specified.
Why is it not working

How to redirect to admin login page in mvc internet application template? (by defaut, it redirect to account/login page))

I have login page in user site and adminlogin page in admin site
I have action
[Authorize]
public ActionResult ChangeProfile(User model)
{
// my code
}
and action in admin site
[Authorize(Roles="Admins")]
public ActionResult UserManager(User model)
{
// my code
}
I like when i access to action ChangeProfile => redirect to login page in user site (if not login)
and when i access to action UserManager => redirect to adminlogin page in admin site (if not login with Admins roles)
Please help me to show me what could i do, thank you so much!
Use custom AuthorizeAttribute and override HandleUnauthorizedRequest.
public class CustomAuthorize: AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
base.HandleUnauthorizedRequest(filterContext);
else
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary("Admin login route"));
}
}
[CustomAuthorize(Roles="Admins")]
public ActionResult UserManager(User model)
{
// my code
}
If you have something like this in your web.config file:
<forms loginUrl="~/Account/LogOn" timeout="2880" />
change it to this but i'm not really sure it works or not but you can try:
<forms loginUrl="/Account/LogOn" timeout="2880" />

How can I implement multiple forms using a single view?

I am having a scenario where I need to implement two forms using a single view... There will be a home page having a form each for LogIn and SignUp (similar to Facebook homepage). I created a view for my home page (Index.cshtml) that contains the razor code for both my forms.
[#using (Html.BeginForm("LogIn", "Home", FormMethod.Post))]
[#using (Html.BeginForm("SignUp", "Home", FormMethod.Post))]
However, upon clicking the 'Log In' button for LogIn form or clicking 'Sign Up' button for SignUp form, the runtime throws an error basically saying that I still need to create views for both LogIn and SignUp actions, even though I have already implemented the HTML forms in my index.cshtml
[NOTE: I am not using ASP.NET membership provider. And this question is generally for two forms, can be any two forms.]
So my question is: Do I really need to create two more views named LogIn.cshtml and SignUp.cshtml? Won't this cause code duplication? I'm quite new to MVC 4 and I hope you understand what I'm trying to do here, so all I want to know is whether there is any other way to implement this? (jQuery, AJAX or something)
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult LogIn()
{
return View();
}
[HttpPost]
public ActionResult LogIn(Account acc)
{
// some code
return View();
}
[HttpGet]
public ActionResult SignUp()
{
return View();
}
[HttpPost]
public ActionResult SignUp(Account acc)
{
// some code
return View();
}
}
You could specify the view you want to be returned:
[HttpGet]
public ActionResult SignUp()
{
return View("LogIn");
}