Objective
The use of forms authentication for user authentication is the most common, but the system to clarify the method of the article is not uncommon, more articles on the web is to introduce a part of the use of the method or the principle of implementation, and more friends are issued to ask how to complete the first to realize the user's registration Login. Therefore, Anders Liu plans to use a practical example in this series of articles to describe how to implement based on the forms authentication:
L User registration (including encrypted storage of passwords)
L User login (including password authentication, set security cookie)
L User Entity substitution (use your own type as the type of HttpContext.User)
The principles of forms authentication are not covered by this article, and you can enter "Forms Authentication", "Forms Authentication", "Forms authentication" in search engines such as Google and other keywords to see more resources. This article describes how to use this technique only from a practical point of view.
Do not use membership
The implementation described in this article does not rely on the membership functionality that ASP. NET 2.0 provides. This is mainly because, if you use membership, you must configure the database with the Aspnet_regsql.exe utility, or you will have to write your own custom MembershipProvider.
If you configure the database with Aspnet_regsql.exe, you will cause a lot of tables or fields in the database that we don't actually need. More importantly, the default SqlMembershipProvider adds ApplicationID columns to many datasheets, which may be intended to put users of multiple applications in a single library, but can be isolated from each other. But the reality is that each application holds user data in its own database. Therefore, the introduction of this applicationid unnecessarily adds additional conditions each time a user is found.
On the other hand, if you consider yourself to achieve a membershipprovider, because the workload is huge, a little outweigh.
However, if you do not use membership, you will not be able to enjoy the convenience of the new login controls in ASP. NET 2.0.
Configuration related to Forms authentication
The,<system.web>/<authentication> configuration section in the Web. config file is used to configure validation. Provide the mode= "forms" property for the <authentication> node to enable forms authentication. A typical <authentication> configuration section is as follows:
<authentication mode= "Forms" >
<forms
Name= ". Aspxauth "
Loginurl= "Login.aspx"
Defaulturl= "Default.aspx"
Protection= "All"
timeout= "30"
Path= "/"
Requiressl= "false"
Slidingexpiration= "false"
Enablecrossappredirects= "false"
Cookieless= "UseDeviceProfile"
Domain= ""
/>
</authentication>
The code above uses the default settings, in other words, if you have a configuration property that is consistent with the above code, you can omit the attribute such as <forms name= "Myappauth"/>. Here's a look at the various properties:
L Name--cookie's name. The Forms authentication may place user credentials in a cookie after validation, and the name attribute determines the cookie's moniker. This configuration value can be obtained with the Formsauthentication.formscookiename property (the Fromsauthentication class is described later).
L loginurl--The URL of the login page. This configuration value can be obtained through the Formsauthentication.loginurl property. When the Formsauthentication.redirecttologinpage () method is called, the client request is redirected to the page specified by the property. The default value for Loginurl is "login.aspx", which means that the ASP is not available even if the property value is not provided. NET will also try to find a page named Login.aspx in the site root directory.
L defaulturl--The URL of the default page. The configuration value is obtained through the Formsauthentication.defaulturl property.
L Protection--cookie Protection mode, the desirable values include all (simultaneous encryption and data validation), encryption (encryption only), Validation (data validation only), and none. For security, this property is typically never set to none.
L TIMEOUT--COOKIE the expiration time.
L Path--cookie's path. This configuration value can be obtained through the Formsauthentication.formscookiepath property.
L requiressl--When you perform the forms authentication, it requires SSL to interact with the server. This configuration value can be obtained through the Formsauthentication.requiressl property.
L slidingexpiration--Whether elastic expiration is enabled, and if the property is set to False, the cookie expires after the timeout time after the first authentication, and if this property is true, the timeout time expires from the last request. This means that, after the first verification, if at least one request is guaranteed to be sent per timeout time, the cookie will never expire. This configuration value can be obtained through the Formsauthentication.slidingexpiration property.
L enablecrossappredirects--Whether the authenticated user can be redirected to another application. This configuration value can be obtained through the Formsauthentication.enablecrossappredirects property. For security reasons, this property is always set to false.
L cookieless--defines the use of cookies and the behavior of cookies. Forms authentication can save user credential information in a session in two ways, using a cookie to record the user's credentials into a cookie, which the browser makes available to the server each time a request is sent. Another way is to use URIs to pass user credentials as additional query strings in the URL to the server. The attribute has four values--usecookies (whenever a cookie is used), UseUri (Never use cookies, only URIs), AutoDetect (detection device and browser, Cookies are only used when the device supports cookies and cookies are enabled in the browser, and usedeviceprofile (only devices are detected, as long as the device supports cookies, regardless of whether the browser supports them). This configuration value can be obtained through the Formsauthentication.cookiemode property. The Formsauthentication.cookiessupported property allows you to use cookies to pass user credentials for the current request.
L Domain--cookie's domain. This configuration value can be obtained through the Formsauthentication.cookiedomain property.
The above introduction to the <system.web>/<authentication>/<forms> node is very brief and is basically an additional description of Anders Liu's personal documentation. For more information about the <forms> node, see the MSDN documentation (HTTP://MSDN2.MICROSOFT.COM/ZH-CN/LIBRARY/1D3T3C61 (vs.85). aspx).
FormsAuthentication class
The FormsAuthentication class is used to assist us in completing forms validation and further completing user login functions. The class is located in the System.Web.Security namespace of the System.Web.dll assembly. This class is typically used directly in Web site projects, and if you use this class in a class library project, make sure that you reference System.Web.dll.
All the properties of the FormsAuthentication class have been described in the previous section. This section describes a few common methods of this class.
The Redirecttologinpage method is used to redirect from any page to the login page, which has two overloaded methods:
public static void Redirecttologinpage ()
public static void Redirecttologinpage (String extraquerystring)
Both methods redirect the browser to the login page (the URL of the login page is indicated by the Loginurl property of the <forms> node). The second overloaded method can also provide additional query strings.
Redirecttologinpage is typically called on any page that is not a login page. In addition to redirecting, the method appends a ReturnUrl parameter to the URL, which is the URL address of the page on which the method was invoked. This is to facilitate login and automatically return to the page before the login.
The RedirectFromLoginPage method is used to jump back to the pre-logon page from the login page. This "Pre-logon" page is specified by the ReturnUrl parameter that is provided when the login page is accessed. If you do not provide a ReturnUrl parameter (for example, instead of using the Redirecttologinpage method to redirect to or direct access to the login page by other means), the method automatically jumps to the <forms> The default page specified by the Defaulturl property of the node.
Also, if the enableCrossAppRedirects property of the <forms> node is set to the path specified by the False,returnurl parameter, it must be a path in the current Web application. Otherwise (such as providing a path under another site) will also return to the default page.
There are two overloaded forms of the RedirectFromLoginPage method:
public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
The username parameter represents the user's identity (such as user name, user ID, and so on), createPersistentCookie parameter indicates whether to "Remember Me", and the strCookiePath parameter represents the cookie path.
In addition to completing redirection, the RedirectFromLoginPage method also stores user credentials that are encrypted (whether encryption depends on the <forms> node's Protection property) into a cookie or URI. In subsequent accesses, as long as the cookie is not expired, the Username property passed in here can be obtained through the HttpContext.User.Identity.Name property.
In addition, FormsAuthentication has a SignOut method for completing user logoff. The principle is to remove user credentials from a cookie or URI.
Well, so far the basic knowledge required to complete, then we will realize the user registration, login and other functions:
ASP. NET MVC builds on ASP. Many of the features of ASP (such as forms authentication, membership) can be used directly in MVC. This article is intended to provide reference code that does not involve too much theoretical knowledge in this area.
This article uses only ASP. Forms authentication and does not use its membership (membership) and role Management (rolemanager) for two reasons: inflexible, and less than MVC.
First, sample project
User.cs is a model file that contains the User class:
public class user{Public int ID {get; set;} public string Name {get; set;} public string Password {get; set;} Public string[] Roles {get; set; }}
Userrepository is a data access class that, for demonstration convenience, does not connect to a database, but instead uses an array as the data source:
public class userrepository{ private static user[] Usersfortest = new[]{ new user{ID = 1, Name = "Bob", Password = "Bob", Roles = new []{"Employee"}, new user{ID = 2, Name = "Tom", Password = "Tom", Roles = new []{"manager"}},
new user{ID = 3, Name = "admin", Password = "admin", Roles = new[]{"Admin"}}, }; public bool ValidateUser (string userName, string password) { return usersfortest . Any (U = u.name = = UserName && U.password = = Password); } Public string[] GetRoles (string userName) { return usersfortest . Where (U = u.name = = userName) . Select (U = u.roles) . FirstOrDefault (); } Public User Getbynameandpassword (string name, string password) { return usersfortest . FirstOrDefault (U = u.name = = Name && U.password = = Password);} }
Second, the user login and authentication method one
Modify AccountController: The original accountcontroller to implement control inversion, the form authentication is abstracted. For demonstration convenience, I'm going to go beyond this section (and register and change the password section):
public class accountcontroller:controller{ private userrepository repository = new Userrepository (); Public ActionResult LogOn () { return View (); } [HttpPost] Public ActionResult LogOn (Logonmodel model, string returnUrl) { if (modelstate.isvalid) { if ( Repository. ValidateUser (model. UserName, model. Password)) { Formsauthentication.setauthcookie (model. UserName, model. RememberMe); if (! String.IsNullOrEmpty (RETURNURL)) return Redirect (RETURNURL); else return redirecttoaction ("Index", "Home"); } else Modelstate.addmodelerror ("", "username or password is incorrect!) "); } return View (model); } Public ActionResult LogOff () { formsauthentication.signout (); Return redirecttoaction ("Index", "Home");} }
Modify Global.asax:
public class mvcapplication:system.web.httpapplication{public mvcapplication () { AuthorizeRequest + = New EventHandler (mvcapplication_authorizerequest); } void Mvcapplication_authorizerequest (object sender, EventArgs e) { IIdentity id = Context.User.Identity; if (ID. isauthenticated) { var roles = new Userrepository (). GetRoles (ID. Name); Context.User = new GenericPrincipal (ID, roles); } } //...}
Add a constructor to mvcapplication that adds a handler for the AuthorizeRequest event.
Code Download: Mvc-formsauthentication-rolesauthorization-1.rar (243KB)
Way Two
This method saves the user's role to the user Cookie and uses the FormsAuthenticationTicket.
Modify AccountController:
public class accountcontroller:controller{Private userrepository repository = new Userrepository (); Public ActionResult LogOn () {return View (); } [HttpPost] public actionresult LogOn (Logonmodel model, string returnUrl) {if (modelstate.isvalid) {User user = Repository. Getbynameandpassword (model. UserName, model. Password); if (user! = null) {FormsAuthenticationTicket ticket = new FormsAuthenticationTicket ( 1, user. Name, DateTime.Now, DateTime.Now.Add (formsauthentication.timeout), Model. RememberMe, user. Roles.aggregate ((i,j) =>i+ "," +j)); HttpCookie cookie = new HttpCookie (Formsauthentication.formscookiename, Formsauthen Tication. Encrypt (ticket)); Response.Cookies.Add (COOKie); if (! String.IsNullOrEmpty (RETURNURL)) return Redirect (RETURNURL); else return redirecttoaction ("Index", "Home"); } else Modelstate.addmodelerror ("", "username or password is incorrect!) "); } return View (model); } public ActionResult LogOff () {formsauthentication.signout (); Return redirecttoaction ("Index", "Home"); }}
Modify Global.asax:
public class mvcapplication:system.web.httpapplication{public mvcapplication () { AuthorizeRequest + = New EventHandler (mvcapplication_authorizerequest); } void Mvcapplication_authorizerequest (object sender, EventArgs e) { var id = Context.User.Identity AS formsidentity; if (id! = NULL && ID. isauthenticated) { var roles = ID. Ticket.UserData.Split (', '); Context.User = new GenericPrincipal (ID, roles); } } //...}
Code Download: Mvc-formsauthentication-rolesauthorization-2.rar (244KB)
Third, role permissions
With either approach, we can use Authorizeattribute in the Controller to implement role-based rights management:
[Authorize (Roles = "Employee,manager")]public ActionResult Index1 () { return View ();} [Authorize (Roles = "manager")]public ActionResult Index2 () { return View ();} [Authorize (users= "admin", Roles = "admin")]public actionresult Index3 () { return View ();}
Iv. Brief description
MVC uses the HttpContext.User property to implement authentication and role management, as well as authorizeattribute role authorization based on HttpContext.User.
Because some do not after the user login, the relevant user information in the session (often seen on the internet), it is a very bad practice to save the user in the session.
Also do not judge role permissions in the Action, you should use Authorizeattribute or its subclasses, the following methods are wrong:
Public ActionResult Action1 () { if (session["User"] = = null) {/**/} /**/}public ActionResult Action2 () { if ( User.Identity = = null) {/**/} if (User.Identity.IsAuthenticated = = False) {/**/} if (User.IsInRole ("admin") = = f alse) {/**/} /**/}
If there are errors or irregularities in this article, please correct me, thank you!
The code used in the project has been made:
Identity verification
Backstage: DateTime ExpiredTime = DateTime.Now.AddMonths (1);
String ssodata = UserName + "," + savelogin.tostring ();
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1, UserName,
DateTime.Now,
ExpiredTime,
Savelogin,
Ssodata,
Formsauthentication.formscookiepath);
String AuthTicket = Formsauthentication.encrypt (ticket);
HttpCookie Lcookie = new HttpCookie (Formsauthentication.formscookiename, AuthTicket);
Lcookie. Expires = DateTime.Now.AddMonths (1);//tick automatic login
RESPONSE.COOKIES.ADD (Lcookie);
Front Desk if (! User.Identity.IsAuthenticated)
Sign Out:
Public ActionResult LogOff ()
{
FormsAuthentication.SignOut ();
Return Redirect (formsauthentication.loginurl);//<system.web> add <authentication mode= "Forms" >< Forms loginurl= "~/portal" timeout= "2880" name= ". Dashboardnetauth "></forms></authentication>
}
ASP. NET MVC: Forms authentication and role Rights Management example