How to redirect the user to a specified page after login

1

I am able to login by user type: admin or common. And I'm using:

  

[Authorize (Roles="Administrator")] and   [Authorize (Roles="Common")]

Within the Controllers I want to restrict by type of user that can access it. But I would like to make the user be redirected to a specific page after he logs in.

My code looks like this:

Web.config

<authentication mode="Forms">
    <forms loginUrl="/Home/Login" timeout="15" />
</authentication>

Global asax.cs

    protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
    {
        var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            if (authTicket != null && !authTicket.Expired)
            {
                var roles = authTicket.UserData.Split(',');
                HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(authTicket), roles);
            }
        }
    }

HomeController.cs

    public ActionResult Login()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Login(string email, string senha, string ReturnUrl)
    {
        Pessoas usuarios = db.Pessoas.Where(t => t.Email == email && t.Senha == senha).ToList().FirstOrDefault();
        if (usuarios != null)
        {
            string permissoes = "";
            permissoes += usuarios.TipoUsuario + ",";
            permissoes = permissoes.Substring(0, permissoes.Length - 1);
            FormsAuthentication.SetAuthCookie(usuarios.Nome, false);
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, usuarios.Email, DateTime.Now, DateTime.Now.AddMinutes(30), false, permissoes);
            string hash = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }
            Response.Cookies.Add(cookie);
            if (String.IsNullOrEmpty(ReturnUrl))
            {
                if (User.IsInRole("Administrador"))
                {
                    return RedirectToAction("DashboardAdm", "Home");
                }
                else
                {
                    return RedirectToAction("DashboardUsuario", "Home");
                }
            }
            else
            {
                var decodedUrl = Server.UrlDecode(ReturnUrl);
                if (Url.IsLocalUrl(decodedUrl))
                {
                    return Redirect(decodedUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
        }
        else
        {
            ModelState.AddModelError("", "E-mail ou Senha estão incorretos");
            return View();
        }
    }

Login.cshtml

@{
ViewBag.Title = "Login";    
}

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="container conteudo">
    <form>
        <div class="row">
            <div class="form-group col-md-8 offset-md-2 col-lg-6 offset-lg-3">
                <label>Email</label>
                <input type="email" class="form-control" id="email" name="email" placeholder="Email" required="required">
            </div>
        </div>
        <div class="row">
            <div class="form-group col-md-8 offset-md-2 col-lg-6 offset-lg-3">
                <label>Senha</label>
                <input type="password" class="form-control" id="senha" value="" name="senha" placeholder="Senha" required="required">
            </div>
        </div>
        <div class="row">
            <div class="form-group col-md-8 offset-md-2 col-lg-6 offset-lg-3">
                <button type="submit" class="btn btn-primary btn-lg btn-block">Entrar</button>
            </div>
        </div>
        <div class="row">
            <div class="form-group col-sm-6 offset-sm-3">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            </div>
        </div>
    </form>
</div>
}
    
asked by anonymous 21.10.2018 / 02:22

1 answer

1

In the Login method on your controller, you have a parameter called ReturnUrl . When calling this method, you can pass the url you want to redirect the logged in user.

Note that in this section you use this parameter to redirect the user:

  var decodedUrl = Server.UrlDecode(ReturnUrl);
  if (Url.IsLocalUrl(decodedUrl))
  {
    return Redirect(decodedUrl);
  }
    
21.10.2018 / 03:14