2
I am able to login by type of user: administrator or common. And I am using:
[Authorize(Roles = "Administrator")] and [Authorize(Roles = "Common")]
Inside the controllers I want to restrict by type of user who can access it. But I would like to redirect the user to a specific page after he logs in.
My code is 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>
}
Your solution solved, but since they are two types of users, always calls the same page, put an IF with User.Isinrole("Administrator") and another IF with User.Isinrole("Common"), did not work, always directs to the role of the first IF.
– Rodrigo Santos
@Rodrigosantos, put here how you implemented this if. Checks if the User object is being populated with the values of this logged in user. If my answer solved your first problem, kindly mark as answer ;)
– Adjair Costa
I added to the code the IF I tried to use.
– Rodrigo Santos
@Rodrigosantos, I noticed that in your code you have a variable "permissions" where you store some values, one of them or you take the property "Type" of the object 'users', is here at this point: string permissions = ""; permissions += users.Typesetting + ","; permissions = permissions. Substring(0, permissions.Length - 1); I believe if you use: users.Typify in your if instead of User.Isinrole should work.
– Adjair Costa
Now that this has worked, thank you very much for your help.
– Rodrigo Santos