asp.net Authentication and authorization

Source: Internet
Author: User
Tags config datetime empty set cookie ticket access visual studio
asp.net

Today I'm bored with leisure. I remember. asp.net authentication. Feel good. Post the following code:
Login.aspx HTML code


1<%@ Page language= "C #" codebehind= "02login.aspx.cs" autoeventwireup= "false" inherits= "authentication. _02login"%>
2<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
34 <HEAD>
5 <title>02Login</title>
6 <meta name= "generator" content= "Microsoft Visual Studio. NET 7.1" >
7 <meta name= "Code_language" content= "C #" >
8 <meta name= "vs_defaultClientScript" content= "JavaScript" >
9 <meta name= "vs_targetschema" content= "http://schemas.microsoft.com/intellisense/ie5" >
Ten </HEAD>
One <body ms_positioning= "GridLayout" >
<form id= "Form1" method= "POST" runat= "Server" >
<font face= "Song Body" >
<table id= "Table1" style= "z-index:102; left:152px; width:446px; Position:absolute; top:80px; Height:72px "
cellspacing= "1" cellpadding= "1" width= "446" border= "1" >
<TR>
<TD>
<asp:label id= "Label1" runat= "Server" > User name:</asp:label></td>
<TD>
<asp:textbox id= "Tbname" runat= "Server" width= "183px" ></asp:textbox></TD>
<TD>
<asp:requiredfieldvalidator id= "RequiredFieldValidator1" runat= "server" errormessage= "username Can't be empty! "Controltovalidate=" Tbname "></asp:requiredfieldvalidator></TD>
</TR>
<TR>
<TD>
<asp:label id= "Label2" runat= "server" > Password:</asp:label></td>
<TD>
<asp:textbox id= "Tbpass" runat= "Server" width= "183px" ></asp:textbox></TD>
<TD>
<asp:requiredfieldvalidator id= "RequiredFieldValidator2" runat= "server" errormessage= "Password not Can be empty! "Controltovalidate=" Tbpass "></asp:requiredfieldvalidator></TD>
</TR>
<TR>
<td><font face= "Song body" > Whether to save cookie</font></td>
<TD>
<asp:checkbox id= "Persistcookie" runat= "Server" ></asp:checkbox></TD>
<TD></TD>
Panax Notoginseng </TR>
</TABLE>
<asp:button id= "Btnloginbetter" style= "Z-INDEX:101; left:288px; Position:absolute; top:240px "
runat= "Server" width= "78px" text= "Login" ></asp:button>
<asp:hyperlink id= "HyperLink1" style= "z-index:103; left:456px; Position:absolute; top:240px "
runat= "Server" Navigateurl= "default.aspx" >HyperLink</asp:HyperLink></FONT>
</form>
</body>
45The Login.aspx.cs code is as follows

private void Btnloginbetter_click (object sender, System.EventArgs e)
{
if (This.tbName.Text = "admin" && this.tbPass.Text = = "Admin")
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,this.tbname.text,datetime.now, DateTime.Now.AddMinutes (a), this. persistcookie.checked, "User");//Create a validation ticket
String cookiestr = Formsauthentication.encrypt (ticket);
HttpCookie cookie = new HttpCookie (FORMSAUTHENTICATION.FORMSCOOKIENAME,COOKIESTR), create a cookie, The cookie name is the name of the Web.config setting, and the value is the encrypted data cookiestr,
if (this. persistcookie.checked)//Determines whether the user selects Save cookies
Cookie. Expires = ticket. expiration;//Get Cookie Expiration time
Cookie. Path = formsauthentication.formscookiepath;//Set Cookie save path
RESPONSE.COOKIES.ADD (cookie);
String strredirect;
strredirect = request["ReturnUrl"];//fetch return URL
if (strredirect = null)
strredirect = "default.aspx";
Response.Redirect (strredirect,true);

}
Else
{
Response.Write ("<script>alert (' account number or password is wrong! '); self.location.href= ' 02login.aspx ' </script> ');
}
}


Default.aspx HTML code

<body ms_positioning= "GridLayout" >
<form id= "Form1" method= "POST" runat= "Server" >
<font face= "Song Body" >
<asp:label id= "Label1" style= "z-index:106; left:224px; Position:absolute; top:72px "runat=" server > User name:</asp:label>
<asp:label id= "Label2" style= "z-index:102; left:220px; Position:absolute; TOP:136PX "runat=" Server > Identity:</asp:label>
<asp:label id= "Lbuser" style= "z-index:103; left:350px; Position:absolute; TOP:79PX "runat=" Server ></asp:Label>
<asp:label id= "LBSF" style= "z-index:104; left:355px; Position:absolute; TOP:133PX "runat=" Server ></asp:Label>
<asp:button id= "Btnlogout" style= "z-index:105; left:261px; Position:absolute; Top:192px "
runat= "Server" text= "Logoff" width= "101px" ></asp:Button></FONT>
</form>
</body>
Post Code

private void Page_Load (object sender, System.EventArgs e)
{
This.lbUser.Text = User.Identity.Name;
if (User.IsInRole ("Admin"))
This.lbSf.Text = "Admin";
Else
This.lbSf.Text = "User";
}

Web Forms Designer generated Code #region Web Forms Designer generated code
Override protected void OnInit (EventArgs e)
{
//
CodeGen: This call is required for the ASP.net Web forms Designer.
//
InitializeComponent ();
Base. OnInit (e);
}

/**////<summary>
Designer supports required methods-do not use the Code editor to modify
The contents of this method.
</summary>
private void InitializeComponent ()
{
This.btnLogout.Click + = new System.EventHandler (This.btnlogout_click);
This. Load + = new System.EventHandler (this. Page_Load);

}
#endregion

private void Btnlogout_click (object sender, System.EventArgs e)
{
FormsAuthentication.SignOut ()//Cancellation ticket
Response.Redirect ("Login.aspx", true); return login.aspx page
}

The


Webconfig configuration is as follows
    <authentication mode= "Forms"
  <forms name=. Securitydemo "loginurl=" Login.aspx ">//. Securitydemo is the cookie name,
  </forms>
    </authentication>

<authorization>
<deny users= "?" />//Deny all anonymous users
<allow roles= "admins"/>//allows administrative level user access
</authorization>
Self-feel ASP write more, generally use session to judge whether the user is legitimate, but in a asp.net project using authentication, basically all the pages have to verify to access, feel a little move strong. However, you can set permissions on the specified page on the Web.config page, setting the code as follows
<location path= "Admin.aspx" >
<system.web>
<authorization>
<deny users= "?"/>
</authorization>
</system.web>
</location>
If you have only a few pages set up as code, it feels acceptable. But the page is too much to make people tired ah.
May be a small project to do more, big items have not been contacted. Please give the expert to the specific use of. Not very grateful.



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.