User, role identity authentication based on FormsAuthentication

Source: Internet
Author: User

In general, when we do access management, the user's correct login after the basic information is saved in the session, the user each time the page or interface data request, get

The user basic information stored in the session to see if he has logged in and can access the current page.

The principle of the session, that is, the server side to generate a sessionid corresponding to the stored user data, and SessionID stored in the cookie, the client after each request will take this

Cookie, the server-side finds data stored on the server side of the corresponding current user based on the SessionID in the cookie.

FormsAuthentication is used by Microsoft to provide us developers with the use of identity authentication. With this authentication, we can store the user name and some user data in a cookie,

It is simple to implement basic identity role authentication through the basic condition setting.

The effect here is to implement role-based access control using the system-provided authorize without using membership.

1. Create Authentication information Ticket

After the user logs in, the user ID and the corresponding role (multiple roles, separated), stored in the ticket.

Use Formsauthentication.encrypt to encrypt the ticket.

Store the encrypted ticket in the response cookie (client JS does not need to read this cookie, so it is best to set up httponly=true to prevent browser attacks from stealing or falsifying cookies). This can be read from the request cookie the next time.

A simple demo is as follows:

        Public ActionResult Login (string uname)         {            if (!string. IsNullOrEmpty (uname))             {                //formsauthentication.setauthcookie (uname,true);                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket                    (   1,                        uname,                        DateTime.Now,                        DateTime.Now.AddMinutes (),                        true,                        "7,1,8",                        "/"                    );                var cookie = new HttpCookie (Formsauthentication.formscookiename,formsauthentication.encrypt (ticket));                Cookies. HttpOnly = true;                HTTPCONTEXT.RESPONSE.COOKIES.ADD (cookie);                return redirecttoaction ("userpage");            }            Return redirecttoaction ("Index");        }

Here FormsAuthenticationTicket the sixth parameter is a string type of UserData, where the current user's role ID is stored, separated by commas.

When the user name "test" is logged in, the client will be prompted with such a record cookie

2. Obtaining Certification Information

After logging in, on the content page, we can obtain the uname information through the User.Identity.Name of the current request, or you can read the cookie in requests to decrypt it, get to ticket, and get uname and userData from it. (That is, the role ID information stored previously).

            viewdata["User"]=user.identity.name;                       var cookie = Request.cookies[formsauthentication.formscookiename];            var ticket = Formsauthentication.decrypt (cookie. Value);            string role = Ticket. UserData;            viewdata["Role" = role;            return View ();

3, through the annotation attribute, realizes the permission access control

Configuring enable form authentication and role management in Web. config

    <authentication mode= "Forms" >      <forms loginurl= "~/login/index" timeout= "2880"/>    </ authentication>    <rolemanager enabled= "true" defaultprovider= "Customroleprovid" >      <providers >        <clear/>        <add name= "Customroleprovid" type= "MvcApp.Helper.CustomRoleProvider"/>      </providers>    </roleManager>

When we add annotation properties to the Controller and action, where does the role set come from? Because there is no membership-based set of authentication, here we also create a custom roleprovider. The name is Customroleprovider and inherits from RoleProvider. Here is your own CustomRoleProvider.cs file created in the helper folder below Mvcapp.

There are many abstract methods in RoleProvider, and we specifically implement only the GetRolesForUser method to get the user role. Here the user role, we can be based on the user ID obtained from the database query, or take the session stored in the, or cookie stored. Here I have already stored the role in the ticket UserData, then get it from the ticket.

public override string[] GetRolesForUser (string username)        {            var cookie = httpcontext.current.request.cookies[ Formsauthentication.formscookiename];            var ticket = Formsauthentication.decrypt (cookie. Value);            string role = Ticket. UserData;            return role. Split (', ');        }

Add annotation properties to the Controller or action that you want to validate, such as this action only allows Roleid to include 1 or 2 or 3 access, while the current user Roleid (7, 1, 8) is the user's access.

       [Authorize (roles= ")]        Public ActionResult Role ()         {            viewdata["user"] = User.Identity.Name;            return View ();           }


P.S.: 1, ticket stored in the cookie expiration time, and close the browser is to remember the current ticket, in the FormsAuthenticationTicket instantiation can set parameters,

2, Role can not be stored in the ticket UserData, can be read directly from the database, UserData can store other information.

3. To flexibly configure the allowed access role of the Controller and action, you can customize the Onauthorization method inside the Authorizeattribute override, in which

Reads the ID of the role that the current page is allowed to access, and checks according to the current user's Roleid. This also enables the flexible configuration of role.

4, ticket in the information, and ultimately stored in the cookie, security or own discretion, personal feel or the UserID and Roleid stored in the session is better.

FormsAuthentication-based user, Role identity authentication (RPM)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.