geof geof - 1 month ago 19
ASP.NET (C#) Question

Authentication in ASP.NET MVC

I begin with ASP.NET and I have a problem with authentication.

This is the code:

web.config

<system.web>
<authentication mode="Forms">
<forms loginUrl="~/users/login" timeout="3000" />
</authentication>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>


login

public ActionResult login()
{
if (Request.HttpMethod == "POST")
{
if (Request.Form["email"] == null || Request.Form["password"] == null)
ViewData["error"] = "form_error";
else
{
User user = this.dal.authUser(
Request.Form["email"],
Request.Form["password"]);
if (user == null)
ViewData["error"] = "auth_error";
else
{
FormsAuthentication.SetAuthCookie(user.id.ToString(), false);
return Redirect("/profiles/" + user.id);
}
}
}
return (View());
}


profile controller

[HttpGet]
public ActionResult get(int id)
{
ViewData["auth"] = false;
if (HttpContext.User.Identity.IsAuthenticated)
ViewData["auth"] = true;
Response.Write(HttpContext.User.Identity.Name);
Profile profile = this.dal.getProfile(id);
if (profile == null)
return View("~/Views/error404.cshtml");
ViewData["profile"] = profile;
return View();
}


and View for get a profile

@using Plume.Areas.Users.Models;

@{
Layout = "~/Views/Layout/layout.cshtml";
Variables.pageTitle = "Profil";
Profile profile = (Profile)ViewData["profile"];
bool auth = (bool)ViewData["auth"];
}

@{
if (auth)
{
<h1>Auth</h1>
}
}

<p>
ceci est le profil de :
@profile.username
<br />
dont l'email est :
@profile.user.email
</p>


So, when I log, a cookie called
.ASPXAUTH
is returned, but in the view for a profile, the
h1
isn't displayed.

What is not correct?

Answer

Please remove or comment below line in Web.Config file.

Web.Config :

 <modules>
  <!--<remove name="FormsAuthenticationModule" />-->
</modules>
Comments