Mark13426
Mark13426

Reputation: 2639

Simple way to authenticate users in ASP.NET MVC without providers

I'm trying to understand how authentication in ASP.NET MVC works. I do not want the built-in MembershipProvider creating a local database behind the scenes. I've also looked at some blog posts talking about custom membership providers. While looking for a much simpler forms authentication model, I found the following:

FormsAuthentication.SetAuthCookie("myusername", true);
FormsAuthentication.SignOut();

The idea is to send the username and salted hashed password to the database and see if they match a record in there. If the user exists, then I pass the username to SethAuthCookie. My questions are:

Upvotes: 1

Views: 2058

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

Should the username be encrypted?

No.

What happens if there are multiple servers and the user is surfing the website? I believe any one of the servers can serve content to the user, so how do they know if the user has been authenticated?

At each request the server reads the authentication cookie that is sent by the client browser and which was generated by the FormsAuthentication.SetAuthCookie call, decrypts it and retrieves the username that is stored inside. Just make sure that you have set the same machine keys for all nodes of your server farm so that no matter which node emitted the authentication cookie, all other nodes can decrypt it.

What's the preferred way of authenticating users in MVC without providers? Am I on the right track or should I be looking into something else?

You are on the right track. You use the FormsAuthentication.SetAuthCookie method to emit the authentication cookie once you have verified that the password hash matches the one of the user in the database and in subsequent actions you could use the User.Identity.Name property to retrieve the currently authenticated user.

I would also recommend you checking out the following article which provides a good overview of how forms authentication works in ASP.NET.

Upvotes: 3

Related Questions