ASP.Net MVC Authentication
I'm aware this has been asked a million times, but all I could find is either very simple scenarios or over-complicated ones that aren't of much use to me (like the huge MembershipProvider sample implementation at MSDN).
Here's my problem : I have a database with a Users table. A User has a username, password and some other important information. What I want is being able to have a page require authentication so if the user has already subscribed to the application he can authenticate using his uname/pwd, otherwise he can sign up by filling in all the required information. No roles, no special privileges, nothing, just plain simple authentication.
I guess it should be something straightforward, I just wanna make sure that it's decoupled enough and don't wanna go writing my custom authentication system if there is a built-in one already available and tested.
Thanks.
EDIT :
Just for clarification, I don't need a custom MembershipProvider, I'm using a SQL Server database so the default provider should work just fine. The problem really is how I can si开发者_StackOverflowmply define my own set of required information for the user.ANSWER :
I ultimately had to derive my own MembershipProvider class and override the methods I was interested in. It was much simpler than I thought ans worked well.Using Visual Studio (2008, 2010), create an ASP.NET MVC2 application (no worries, I'm not suggesting to keep it, just use it for studying). In the created code have a look at the interface IMembershipService:
public interface IMembershipService {
int MinPasswordLength { get; }
bool ValidateUser(string userName, string password);
MembershipCreateStatus CreateUser(string userName, string password, string email);
bool ChangePassword(string userName, string oldPassword, string newPassword);
}
In your application you can implement this interface any way you like, e.g. with a class that uses the information you have stored in the Users table.
Another example would be a class that uses a WCF-based web service. This is an approach I used in one of my recent projects.
All the rest is already wired up and ready to go.
That's really simple, just call
FormsAuthentication.SetAuthCookie(userName, rememberMe);
and put an [Authorize]
attribute on the controllers or actions that you want to restrict access
also, in case you're gonna need roles in future you can look here
http://code.google.com/p/asms-md/source/browse/trunk/WebUI/FormAuths.cs i store the roles in the ticket here
精彩评论