0
votes

I am upgrading my project from asp.net web forms to MVC4, step by step. In the first step I changed the login page and few other pages. I am using forms authentication, with my own logic (no membership) - I check the username/password against a database table. If it is OK the user is redirected to its destination. My login code is:

Web.config:

<authentication mode="Forms">
    <forms loginUrl="~/LogIn" name=".ASPXFORMSAUTH" timeout="150" />
</authentication>
<authorization>
    <deny users="?" /> 
</authorization>

Login Controller:

[AllowAnonymous]
[HttpPost]
public ActionResult AjaxLogin(FormCollection postedFormData)
{
    try
    {
        string userName = postedFormData["Login_UserName"];
        string password = postedFormData["Login_Password"];
        UserEntity userEntity = new UserEntity(Utilities.AuthenticateUser(userName, password, 1));

        Session["UserEntity"] = userEntity;

        FormsAuthentication.SetAuthCookie(userEntity.Key.Id.ToString(), false);

        return Json(new { redirectToUrl = "./AccountSelection", error = "false", lan = Thread.CurrentThread.CurrentUICulture.ToString() });
    }
    catch (Exception ex)
    {
         return Json(new { redirectToUrl = "", error = ExceptionHandler.HandleException(ex), lan = Thread.CurrentThread.CurrentUICulture.ToString() });
    }
}

When I try to login I get http 302 and redirected back to login. If I remove the "authorization" section on web.config it will work fine, but now I have two problems:

  1. I have to put [authorize] attribute on every controller
  2. My webforms will not be inside forms authentication (can be accessed directly with no login!!)

What am I doing wrong?

1

1 Answers

2
votes

If you're defining your authorization in web.config, you don't need an AllowAnonymousAttribute.

Having said that, you don't appear to be adding AjaxLogin to your authorization list. This is necessary, because the Ajax request will otherwise be blocked. You need both ~/Login and ~/Account/AjaxLogin paths. You may also need a ~/Account/Login path, but i'm not certain of that.