How to use login in different areas in asp.net mvc

4

I'm creating an application, where it has more than Area , which is restricted. (as shown in the image below).

Myquestionishowtologinindifferentareas?

Details:

SincetheusersintheAdminareaandintheSystemareaaredifferent,each   oneissavedtoadifferenttableinthedatabase.

Authenticationisperformedwithforms,andauthenticationfortheAdminareaalreadyexists:

<authenticationmode="Forms">
      <forms loginUrl="~/Autenticacao/Login" defaultUrl="Admin/Home" timeout="2880" />
    </authentication>
    
asked by anonymous 04.11.2016 / 19:27

1 answer

2

In your% of%, remove the Web.config part.

<authentication mode="Forms">
      <forms loginUrl="~/Autenticacao/Login" timeout="2880" />
</authentication>

In action defaultUrl="Admin/Home" , you can redirect users to different places, something like:

public ActionResult Login(String LoginStr, String SenhaStr, bool ManterConectado)
{
    // Seu código de login
    return RedirectPaginaInicial(usuario);
}

// Função para retornar a página inicial de cada usuário
private RedirectToRouteResult RedirectPaginaInicial(Usuario usuario)
{
     if (usuario.Areas == (int)PaginaPrincipal.ADMIN)
         return RedirectToAction("Lista", "PaginaAdministrador");

     if (usuario.Areas == (int)PaginaPrincipal.SISTEMA)
          return RedirectToAction("Lista", "Sistema");

     return RedirectToAction("Lista", "Agenda");
}

In this case, Autenticacao/Login is PaginaPrincipal :

public enum PaginaPrincipal
{
     [Display(ResourceType = typeof(Translate.Enum), Name = "Administrador")]
     ADMIN = 1,

     [Display(ResourceType = typeof(Translate.Enum), Name = "Sistema")]
     SISTEMA = 2,
}

If you do not just want a redirect, as Gypsy says, you have this article " How to Use Areas in ASP.NET MVC 5? , explaining step by step how to use the login procedure by areas, is quite complete.

To make the answer more complete, I removed those snippets from the article. You will have to include a new enum

<li>@Html.ActionLink("ADMIN", "Index", "Home", new { area = "Admin" }, null)</li>
<li>@Html.ActionLink("SISTEMA", "Index", "Home", new { area = "Sistema" }, null)</li>

And insert the @Html.ActionLink attribute above the name of the [Authorize] :

[Authorize]
public class HomeController : Controller
{
    // GET: Admin/Home
    public ActionResult Index()
    {
        return View();
    }
}

Open the page HomeController in _Layout.cshtml and add the lines of Areas/Admin/Views/Shared that shows the name of the logged in user, just below the div menu.

@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
<div class="text-info">
    @User.Identity.Name
</div>
    
04.11.2016 / 20:31