How to get a user to log in to see any content using ASP.NET MVC 4

I am working on an ASP.NET MVC 4 application and use the "SimpleMembershipProvider". The application will be used on the intranet, and there will be no content available for unauthorized users, so I want to force a login before providing the user with actual site content.

I think this should be a pretty trivial task, but for the first time I have to implement such logic, and I also want to make the MVC 4/SimpleMemebrship , so I ask for advice.

What I think should be implemented is to first add this to web.config:

 <authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="15" slidingExpiration="true" enableCrossAppRedirects="false" protection="All" /> </authentication> 

In the end, I will not have actions that allow anonymously, so I think it's better to put it here.

And changing my default route to:

  routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional } ); 

Which, as I see it, will be the only action that will allow anonymously. However, I'm a little worried about changing the default route to Login I'm not sure if this will not lead to unexpected flaws.

I also have an idea to keep the default structure created by MVC 4 Internet Template , and just leave the Index action of the Home controller taking responsibility, but I don’t like this scenario because the logic is clear - the user must log in to get which either access, and even Home/Index is some access in my mind.

So what is the way to implement this behavior? What are the main steps, changes that I have to make to realize this right?

+6
source share
1 answer

This can be done by registering the Authorize attribute as a global filter. The following is an example of what your RegisterGlobalFilters method looks like:

 public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new AuthorizeAttribute()); } 

with this in place, you must allow anonymous users access to the login page. To do this, you annotate your login action method with the AllowAnonymous attribute.

 [AllowAnonymous] [HttpGet] public ActionResult Login() { ... } 

Do the same for the login action method that receives the POST request.

+19
source

Source: https://habr.com/ru/post/958670/


All Articles