Use Forms for authentication in ASP. NET

Source: Internet
Author: User
Introduction

ASP. in. net, there are three authentication methods: Windows, forms, and passport. Windows authentication is based on form authentication, and authentication code needs to be written on each page, which is relatively flexible, but the operation is too complicated; passport uses a centralized authentication method provided by Microsoft, which features high security but complicated implementation. The most suitable for small and medium-sized projects is forms-based authentication. It collects the defined files and directories on a page for verification and sends the user's identity back to the client's cookie, when the user accesses the website again within the period when the cookie has not expired, the cookie will be sent to the server together with the identity cookie. The authorization settings of the server can be controlled by different users in different directories. Its permission model is user-role model, which can meet the needs of most application scenarios.

Implementation

In the Application Scenario, all users have all permissions. In this case, there is only one role or no role. In this case, you only need to verify whether the cookie exists. The following describes how to implement the application step by step.

First, create a website project and modify web. config:

<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="true">
</compilation>
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="~/login.aspx" protection="All"></forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</configuration>

Note that the authentication section is configured with the authentication method, and the loginurl is the default authentication page. If you directly access other pages, the system returns to this page for authentication. The name attribute value is the cookie name. It also has the following attributes:

Cookieless: Defines whether to use cookies and cookies. Usercookies specify that cookies are used on all devices; useuri indicates that cookies are never used; autodetect indicates that cookies are used by adaptive devices; usedeviceprofile indicates that cookies are supported by browsers.

Defaurl URL: Defines the default URL for redirection after authentication.

Timeout: Specifies the cookie expiration time.

Domain: Specifies the domain where the cookie is located. You must know that the cookie cannot be cross-origin.

Protection: Set it to all to verify the confidentiality and integrity of the ticket with the specified form identity. As a result, the algorithm specified on the machinekey element is used to encrypt the authentication ticket, and the hash algorithm specified on the same machinekey element is used to sign the ticket.

Use the authorizaion element to configure the user authorization model,

Use the allow element to store users and roles that allow access, and use the deny element to store users and roles that reject access. Users, roles, and verbs are used to control users, roles, and HTTP transmission methods respectively. For example:

      <authorization>
<allow users="user1,user2,user3" roles="admin,submitter" verbs="GET,HEAD,POST,DEBUG" />
<deny users="user4" roles="guest" verbs="" />
</authorization>

User1, user2, and user3 are authorized to access table store. user4 is not allowed to access table store. The access permissions are admin and submitter, and get. Here we use user = "? "Represents all users.

Create login. aspx. The page layout is as follows:

The authentication code and cookie writing code are as follows:

// Storage role permission string [] userroles = new string [] {"1", "1", "0"}; // isadmin, iseditor, ispublisherstring userdata = username + "," + String. join (",", userroles); // create a ticket formsauthenticationticket ticket = new formsauthenticationticket (1, username, datetime. now, datetime. now. adddays (30), true, userdata); // encrypted ticket string authticket = formsauthentication. encrypt (ticket); // store as cookiehttpcookie cookie = new httpcookie (formsauthentication. formscookiename, authticket); // cookie. domain = "51obj.cn"; cookie. expires = ticket. expiration; response. cookies. add (cookie); response. redirect ("index. aspx ");

In this way, the cookie is written to the client, and the user accesses other pages. If the cookie does not exist, it will jump to the login. ASPX page for verification.

The username and role information can be read:

        HttpCookie cookie = Request.Cookies[".ASPXAUTH"];        string[] userData = ((System.Web.Security.FormsIdentity)this.Context.User.Identity).Ticket.UserData.Split(',');        string userName = userData[0];        bool isAdmin = Convert.ToBoolean(Convert.ToInt32(userData[1]));        bool isEditor = Convert.ToBoolean(Convert.ToInt32(userData[2]));        bool isPubliher = Convert.ToBoolean(Convert.ToInt32(userData[3]));

Code download

Related Article

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.