woggles
woggles

Reputation: 7444

Where is the proper place to put this authentication logic?

We have an old classic asp app that is used to manage and launch our other web applications.

The way it launches apps is as follows:

<form name="frmMain" action="http://xxxx/mvc3app/Index" target=_self method=post>
<script language="javascript">
frmMain.submit();
</script>

User login and password is passed through as part of the request.

To Authenticate the user in the ASP.NET app I call the following AuthenticateUser function:

public bool AuthenticateUser()
{

 var userName = Context.Request["txtName"];
 var password = Context.Request["txtPassword"];   

    if (Membership.ValidateUser(userName, password))
    {
       FormsAuthentication.SetAuthCookie(userName, true);              
    }
}

I assumed that the correct place to call AuthenticateUser would be in the Session_Start() method in global.asax but it doesn't seem that this method is called when submitting "frmMain". It seems to work intermittently - if I close IE completely, try again and then enter the URL manually.

void Session_Start(object sender, EventArgs e)
{
   Log("In Session Start");
   AthenticateUser();
}

Where would be the correct place to in my ASP.NET app to authenticate users?

Here is a screeny from dev tools of the forms auth failing - Session_Start() isn't called.

enter image description here

EDIT

Looks like this wasn't working because the IsAuthenticated property is only set on subsequent requests which was causing auth to fail on the index action.

I'll test this now but see Who sets the IsAuthenticated property of the HttpContext.User.Identity

Solution:

First Error was not redirecting after calling SetAuthCookie which was causing the Index view to fail auth.

I also realised there is no need to place this in global.asax but I could rather redirect to a LogOn action instead of going directly to the index action:

public ActionResult LogOn()
    {            

    var userName = Context.Request["txtName"];
    var password = Context.Request["txtPassword"];

            if (Membership.ValidateUser(userName, password))
            {
                FormsAuthentication.SetAuthCookie(userName, false);
                return RedirectToAction("Index", "Index");
            }

            else
            {
               return RedirectToAction("IncorrectLogin", "Index");
            }
    }

Upvotes: 1

Views: 382

Answers (1)

nyxthulhu
nyxthulhu

Reputation: 9762

I think a controller action would be the best place, its a good idea to keep controller actions to a minimum so it doesn't get bloated. But if the action isn't touching too many layers it seems like a good fit.

If you were doing any "weird" stuff with session manipulation you can still use Session_Start though. But avoid it if you can, nothing like magic happening all over the place to confuse you on your own application exec path :D

Upvotes: 1

Related Questions