The ASP.NET MVC Website Template comes pre-configured to use SqlMembershipProvider which manages storage of membership information for an ASP.NET application in a SQL Server database.
But before you can use this properly you will need to setup your database, which will be very easy because Microsoft shipped .NET 2.0 with a nice utility to do it! You can find this on your computer, at this path C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe
Your database should have these tables:
Now lets tell our ASP.NET MVC Website’s configuration where to find this database. Open the web.config and change the ApplicationServices connection string to point to your SQL Server. You should now rebuild your solution to avoid any problems in the next step!
- <connectionStrings>
- <add name="ApplicationServices"
- connectionString="Data Source=localhost;
- Initial Catalog=database;
- Persist Security Info=True;
- User ID=user;
- Password=password"
- providerName="System.Data.SqlClient"
- />
- </connectionStrings>
It’s all good and nice but now we need Users in this database otherwise it’s completly useless! So open up your ASP.NET MVC Solution in Visual Studio and go to Project » ASP.NET Configuration. This will open the ASP.NET Web Application Administration website. In the Security tab you can Add/Manage Users and Roles. For the moment, add a user so we can try the login. I’ve added userMike.
You can now run your application and click on [ Log On ] at the top right corner of the page, this will redirect you the the logon form.
If you entered the correct credential you should be redirected to the home page of the site and you will see your name and a Log Off button instead of the Log On button.
Well congraticulations! You now have SqlMembershipProvider working on your website, wasn’t so hard, was it? Not ingle line of code required! I’ll be posting again soon to show you how to use Roles in your applications
Tham khảo : http://helios.ca/2009/04/22/aspnet-mvc-sqlmembershipprovider/
Một số hàm thường dùng trong ASP Membership Provider
Tháng Một 14, 2009 — khanhptTóm lượt từ các tutorial tại www.asp.net
Create User:
link gốc : http://www.asp.net/learn/security/tutorial-05-cs.aspx
MembershipCreateStatus createStatus;
MembershipUser newUser = Membership.CreateUser(Username.Text, Password.Text, Email.Text, passwordQuestion, SecurityAnswer.Text, true, out createStatus);
kiểm tra quá trình create user bằng creatStatus.
Kiểm tra quyền của user:
link : http://www.asp.net/learn/security/tutorial-08-cs.aspx
Get a reference to the currently logged on user
MembershipUser currentUser = Membership.GetUser();
Determine the currently logged on user's UserId value
Guid currentUserId = (Guid)currentUser.ProviderUserKey;
Kiểm tra Role của user hiện tại:
bool allow = (
currentUser
.IsInRole("Role cần kiểm tra"))
Tạm thời copy 2 em thường dùng nhưng cũng thường quên nhất