ASP.NET Forms Authentication - When to use?

2019-05-27 02:28发布

问题:

I am not able to decide whether I should go for Forms Authentication ? Forms authentication is often used for personalization, where content is customized for a known user. I do not have such requirement. I have usernames and passwords in the DB and need to authenticate the users against the DB ? What is the best recommended practice to achieve the same in ASP.NET 2.0 ?

回答1:

TL;DR: The FormsAuthenication class has nothing to do with passwords. You need to use it to keep users logged in to your website. In order to validate the passwords, use the Membership class or your own custom system.


From the documentation for the FormsAuthentication class:

Forms authentication enables user and password validation for Web applications that do not require Windows authentication. With forms authentication, user information is stored in an external data source, such as a Membership database, or in the configuration file for an application. Once a user is authenticated, forms authentication maintains an authentication ticket in a cookie or in the URL so that an authenticated user does not need to supply credentials with each request.

If you look at the class definition for FormsAuthentication, you'll see an Authenticate method. The documentation says "Validates a user name and password against credentials stored in the configuration file for an application." You don't want to use this because you want to store users and passwords in a database, not the config file. This is the ONLY method related to passwords in the whole FormsAuthentication class.

The correct way to issue a forms ticket is with the SetAuthCookie method, which does not take a password. So how/where do you check the password?

Answer: Membership (or something custom).

The ASP.NET version 2.0 membership feature provides secure credential storage for application users. It also provides a membership API that simplifies the task of validating user credentials when used with forms authentication. Membership providers abstract the underlying store used to maintain user credentials.

Membership is a large topic and you really need to spend some time researching it and writing a test application. I'd read at least the first three articles in the Multipart Series on ASP.NET's Membership, Roles, and Profile.

After you're done reading that, you're probably going to wonder if you should write your own custom Membership provider. You might want to take a look at some of the answers here on SO for guidance on that stackoverflow or start a new question when that comes up.



回答2:

Forms Authentication is used for authentication, you can use the membership information to customize pages, but you don't have to.