For Login, remember my function, and verification code login verification, verification code verification

Source: Internet
Author: User

For Login, remember my function, and verification code login verification, verification code verification

1. during login, we often encounter that a page accessing the system cannot be logged on. We need to go to the login page. Although we are not visiting the login page, how does this happen? In addition, you can enter the "remember me" and "Verification Code" in the login process.

Today I wrote a demo about the login verification code and the remember me function.

2. Session and Cookies are mainly used here. Cookies store client login information and Session Access verification code information.

Logon page: Login. aspx

<Script>
Function checkcode (){
Var vcode = document. getElementById ("checkcode ");
Vcode. src = vcode. src + '1 ';
}
Window. onload = function (){
Var did = document. getElementById ("width"). style. width;
Did = window. innerWidth-100;
}
</Script>

<Form id = "form1" runat = "server" method = "post">
Username: <input type = "text" name = "username" value = "<% = username %>"/>
<Br/>
<Br/>
Password & nbsp; Code: <input type = "password" name = "upwd" value = "<% = upwd %>"/>
<Br/>
Verification Code: <input type = "text" name = "Vcode"/>

<A href = "Javascript: checkcode ()"> you cannot see it clearly. Change it to another one. </a>
<Br/>
<Br/>
<Div id = "width">
<Div style = "margin: 0 auto">
Remember me: <input type = "checkbox" name = "echeck"/>
</Div>
</Div>
<Br/>
<Input type = "submit" value = "login"/>
</Form>

Login processing: Login. aspx. cs

Public partial class Login: System. Web. UI. Page
{
Protected string username {get; set ;}
Protected string upwd {get; set ;}
Protected void Page_Load (object sender, EventArgs e)
{
String vcode = Request ["Vcode"];
// Load the page for the first time. If the verification code is empty, cache the page.
If (string. IsNullOrEmpty (vcode ))
{
HttpCookie cooike = Request. Cookies ["jun"];
If (cooike! = Null ){
String uinfo = Encoding. UTF8.GetString (Convert. FromBase64String (cooike. Value ));
Username = uinfo. Split ('_') [0];
Upwd = uinfo. Split ('_') [1];
}
}
Else {
If (vcode! = Null)
{
If (vcode. Equals (Session ["vcode"]. ToString (), StringComparison. CurrentCultureIgnoreCase ))
{
// The verification code is correct.
String SQL = "select count (*) from tb_Userinfo where userName = @ uname and userpwd = @ upwd ";
SqlParameter [] ps = new SqlParameter [] {
New SqlParameter ("@ uname", Request ["username"]),
New SqlParameter ("@ upwd", Request ["upwd"])
};
Int count = Convert. ToInt32 (SqlHelper. ExecuteScalar (SQL, ps ));
// The user information is correct
If (count> 0)
{
// Remember me if it is checked
If (! String. IsNullOrEmpty (Request ["echeck"])
{
// Login successful, access Cookies
String uinfo = Request ["username"] + "_" + Request ["upwd"];
// Convert to 64-bit encoding
Uinfo = Convert. ToBase64String (Encoding. UTF8.GetBytes (uinfo ));
HttpCookie cooike = new HttpCookie ("jun", uinfo)
{
Expires = DateTime. Now. AddDays (14)
};
Response. Cookies. Add (cooike );
}
Session ["userinfo"] = 1;
Response. Redirect ("Index. aspx ");
}
Else
{
Response. Write ("incorrect user name or password ");
}
}
Else
{
Response. Write ("Verification code error ");
}
}
}
}
}

Go to the Index page and go to the page. First, use the SessionStatus class inherited by Index. Here we encapsulate a method.

Protected void p_load (object sender, EventArgs e)
{
If (Session ["userinfo"] = null)
{
Response. Redirect ("Login. aspx ");
}
}

On the Login. aspx. cs page, store Session ["userinfo"] = 1 to verify that the non-Logon page is valid.

Verification code I mainly reference a general handler: ValidateCode. ashx

Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "image/jpeg ";
CreateImage (CreateRandomCode (4). Save (context. Response. OutputStream, ImageFormat. Jpeg );
}
// Generate random code
Private string CreateRandomCode (int iLength)
{
Int rand;
Char code;
String randomCode = String. Empty;

// Generate a verification code of a certain length
System. Random random = new Random ();
For (int I = 0; I <iLength; I ++)
{
Rand = random. Next ();
If (rand % 3 = 0)
{
Code = (char) ('A' + (char) (rand % 26 ));
}
Else
{
Code = (char) ('0' + (char) (rand % 10 ));
}
RandomCode + = code. ToString ();
}

Console. WriteLine ("--------------------------" + HttpContext. Current. Session. SessionID );
HttpContext. Current. Session ["vcode"] = randomCode;
Return randomCode;
}
// Create a random Image
Private Image CreateImage (string strVerifyCode)
{
Bitmap map;
Try
{
Int iRandAngle = 45; // random Rotation Angle
Int iMapWidth = (int) (strVerifyCode. Length * 21 );
Map = new Bitmap (iMapWidth, 28); // create an image background

Graphics graph = Graphics. FromImage (map );
Graph. Clear (Color. AliceBlue); // Clear the screen and fill in the background.

Graph. SmoothingMode = System. Drawing. Drawing2D. SmoothingMode. AntiAlias; // Mode


Random rand = new Random ();

// Generate background noise
Pen blackPen = new Pen (Color. LightGray, 0 );
For (int I = 0; I <50; I ++)
{
Int x = rand. Next (0, map. Width );
Int y = rand. Next (0, map. Height );
Graph. DrawRectangle (blackPen, x, y, 1, 1 );
}


// Rotate the verification code to prevent Machine recognition
Char [] chars = strVerifyCode. ToCharArray (); // split the string into a single character array

// Text distance
StringFormat format = new StringFormat (StringFormatFlags. NoClip );
Format. Alignment = StringAlignment. Center;
Format. LineAlignment = StringAlignment. Center;

// Define the color
Color [] c = {Color. Black, Color. Red, Color. DarkBlue, Color. Green, Color. Orange, Color. Brown, Color. DarkCyan, Color. Purple };
// Define the font
String [] font = {"Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", ""};

For (int I = 0; I <chars. Length; I ++)
{
Int cindex = rand. Next (7 );
Int findex = rand. Next (5 );

Font f = new System. Drawing. Font (font [findex], 13, System. Drawing. FontStyle. Bold); // Font style (parameter 2 indicates the Font size)
Brush B = new System. Drawing. SolidBrush (c [cindex]);

Point dot = new Point (16, 16 );

Float angle = rand. Next (-iRandAngle, iRandAngle); // degrees of Rotation

Graph. TranslateTransform (dot. X, dot. Y); // move the cursor to the specified position
Graph. RotateTransform (angle );
Graph. DrawString (chars [I]. ToString (), f, B, 1, 1, format );

Graph. RotateTransform (-angle); // go back
Graph. TranslateTransform (2,-dot. Y); // move the cursor to the specified position
}

Graph. drawRectangle (new Pen (Color. black, 0),-chars. length * 18, 0, map. width-1, map. height-1); // draw a border

}
Catch (ArgumentException ex)
{
Map = null;
Throw ex;
}
Return map;
}
Public bool IsReusable
{
Get
{
Return false;
}
}

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.