Tuesday, 7 March 2017

Show Asp.net Captcha on 3 Failed Login Attempts

3/07/2017 - By Pranav Singh 0

This article will show you in asp.net to display captcha on 3 failed login attempts using c#. In this if user add 3 time invalid login detail on 4th time a captcha will come.

For first we will create a table for user login.

 Now we will create an asp.net application an add the below code for creating the captcha code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Captcha.aspx.cs" Inherits="Shoping_Cart.Captcha" %>

Here I have removed all the html tag of the page and  left only the page tag. Now check the code for captcha.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Shoping_Cart
{
    public partial class Captcha : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string[] strArray = new string[36];
            strArray = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

            Random autoRand = new Random();
            string strCaptcha = string.Empty;
            for (int i = 0; i < 6; i++)
            {
                int j = Convert.ToInt32(autoRand.Next(0, 62));
                strCaptcha += strArray[j].ToString();
            }
            Session["Captcha"] = strCaptcha;
            ImageConverter converter = new ImageConverter();
            Response.BinaryWrite((byte[])converter.ConvertTo(CaptchaGeneration(strCaptcha), typeof(byte[])));
        }
        public Bitmap CaptchaGeneration(string captchatxt)
        {
            Bitmap bmp = new Bitmap(133, 48);
            using (Graphics graphics = Graphics.FromImage(bmp))
            {
                Font font = new Font("Tahoma", 14);
                graphics.FillRectangle(new SolidBrush(Color.Gray), 0, 0, bmp.Width, bmp.Height);
                graphics.DrawString(captchatxt, font, new SolidBrush(Color.Gold), 25, 10);
                graphics.Flush();
                font.Dispose();
                graphics.Dispose();
            }
            return bmp;
        }
    }
}

In above code I have saved the captcha code value into session. By using this session I will validate the user entered captcha.

Now we will create the login form .

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login-Captcha.aspx.cs" Inherits="Shoping_Cart.Login_Captcha" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Asp.Net Captcha C#</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table width="100%">
                <tr>
                    <td style="text-align: right;">User Id</td>
                    <td style="text-align: right;">
                        <asp:TextBox ID="txtUSerId" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td style="text-align: right;">Password</td>
                    <td style="text-align: right;">
                        <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox></td>
                </tr>
                <tr>
                    <td style="text-align: center;" colspan="2">
                        <asp:Image runat="server" ImageUrl="~/Captcha.aspx" ID="imgCaptcha"></asp:Image><br />
                        <asp:TextBox ID="txtcaptchaValue" runat="server"></asp:TextBox>  <br />
                        <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
                        <br />
                        <asp:Label ID="lblmessage" runat="server" Style="color: #FF3300" Text=""></asp:Label></td>
                </tr>
            </table>


        </div>
    </form>
</body>
</html>

In above code I have created the login form with captcha code. Now we will check the code.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Shoping_Cart
{
    public partial class Login_Captcha : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            imgCaptcha.Visible = false;
            txtcaptchaValue.Visible = false;
            if (Session["LoginCount"] != null)
            {
                if (Convert.ToInt32(Session["LoginCount"]) >= 3)
                {
                    imgCaptcha.Visible = true;
                    txtcaptchaValue.Visible = true;
                }
            }

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string captcha = "";
            if (Session["Captcha"] != null)
            {
                captcha = Session["Captcha"].ToString();
            }
            try
            {
                DataSet ds = new DataSet();

                SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=Demo;Integrated Security=True");
                string query = "select * from UserLoginDetail Where [UserId]='" + txtUSerId.Text + "' and [Password]='" + txtPassword.Text + "';";
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(query, con);
                da.Fill(ds);
                con.Close();
                if (ds.Tables[0].Rows.Count > 0 && Convert.ToInt32(Session["LoginCount"]) >= 3)
                {
                    if (Convert.ToInt32(Session["LoginCount"]) >= 3)
                    {
                        if (captcha == txtcaptchaValue.Text)
                        {
                            Response.Redirect("SuccessPage.aspx");
                        }
                        else
                        {
                            lblmessage.Text = "Please enter a valid captcha.";
                        }
                    }
                    else
                    {
                        Response.Redirect("SuccessPage.aspx");
                    }
                }
                else
                {
                    if (Convert.ToInt32(Session["LoginCount"]) >= 3)
                    {
                        if (captcha == txtcaptchaValue.Text)
                        {
                            Session["LoginCount"] = Convert.ToInt32(Session["LoginCount"]) + 1;
                            lblmessage.Text = "Please enter a valid login detail.";
                        }
                        else
                        {
                            lblmessage.Text = "Please enter a valid captcha.";
                        }
                    }
                    else
                    {
                        Session["LoginCount"] = Convert.ToInt32(Session["LoginCount"]) + 1;
                        lblmessage.Text = "Please enter a valid login detail.";
                    }
                }
            }
            catch
            {

            }

        }
    }
}

In above I have created a session named as LoginCount. In this I am saving the fail login count. After 3 fail login I am enabling the captcha.

Now we have done run the application to check the output.

About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

0 comments:

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Global Classified : Connectseekers.com
© 2014 aspdotnet-pools.com Designed by Bloggertheme9.
back to top