Archive

Posts Tagged ‘ASP.Net Handler’

Implementing ASP.Net Forms Authentication with Active Directory Membership Provider

June 29th, 2010 Anuraj P No comments

ActiveDirectoryMembership provider is used manage users against Active Directory, which helps to create Single Sign On for intranet application. Here is a basic implementation, which used to Authenticate users against Active Directory, using Login Control.

We need to modify the web.config, like the implementation of Forms Authentication in ASP.Net.

Create / Add a connection string to active directory database.

<connectionStrings>
<add name="ADConnectionString" connectionString="LDAP://DOMAIN.SUBDOMAIN/DC=DOMAIN,DC= SUBDOMAIN "/>
</connectionStrings>

Configure Membership node in the web.config with ActiveDirectoryMembershipProvider.

<membership defaultProvider="MembershipADProvider">
  <providers>
    <add name="MembershipADProvider"
         type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
         applicationName="dotnetthoughts"
         connectionStringName=" ADConnectionString "
         attributeMapUsername="sAMAccountName"/>
  </providers>
</membership>

You can also provide the Username / Password in this using connectionUsername , connectionPassword attributes.

Modify the Authentication mode and Authorization nodes for controlling the access permissions. Currently I am using Forms Authentication defaults. (default.aspx – Home Page, and Login.aspx – Login Page)

<authentication mode="Forms" />
<authorization>
    <deny users="?" />
    <allow users="*" />
</authorization>

Almost done. Now drag and drop Login control from Toolbox > Login tab to Login.aspx. Run the application, say OK to the Debug mode confirmation from Visual Studio. As we are configured the Authentication provider we don’t need to write any Code to Authentication.

If you don’t want to use login control, you can do something like this in the code behind for the authentication.

if (Membership.ValidateUser(this.txtUsername.Text, this.txtPassword.Text))
{
    FormsAuthentication.RedirectFromLoginPage(this.txtUsername.Text, false);
}
else
{
    Response.Write("Authentication failed.\nUsername / Password Invalid");
}

Thanks to Sreenaja for the initial implementation. Happy Coding :)

Captcha using ASP.Net and C#

September 15th, 2009 Anuraj P 4 comments

Few days back, I got some question related to Captcha (security mechanism, which helps web masters to avoid spam) in a Forum. So I thought of implementing one. I got few nice scripts in Code Project, its a simple implementation, no too much logic and not too complex to understand. Also I am using an HTTP Handler instead of ASPX Page, for the implementation.

using (Bitmap b = new Bitmap(150, 40, PixelFormat.Format32bppArgb))
        {
            using (Graphics g = Graphics.FromImage(b))
            {
                Rectangle rect = new Rectangle(0, 0, 149, 39);
                g.FillRectangle(Brushes.White, rect);

                // Create string to draw.
                Random r = new Random();
                int startIndex = r.Next(1, 5);
                int length = r.Next(5, 10);
                String drawString = Guid.NewGuid().ToString().Replace("-", "0").Substring(startIndex, length);

                // Create font and brush.
                Font drawFont = new Font("Arial", 16, FontStyle.Italic | FontStyle.Strikeout);
                using (SolidBrush drawBrush = new SolidBrush(Color.Black))
                {
                    // Create point for upper-left corner of drawing.
                    PointF drawPoint = new PointF(15, 10);

                    // Draw string to screen.
                    g.DrawRectangle(new Pen(Color.Red, 0), rect);
                    g.DrawString(drawString, drawFont, drawBrush, drawPoint);
                }
                b.Save(context.Response.OutputStream, ImageFormat.Jpeg);
                context.Response.ContentType = "image/jpeg";
                context.Response.End();
            }
        }

I wrote the code in the Process Request event in HTTPHandler.
And to use this in your pages you can create an IMG tag with src attribute pointing to this.

<img src="myhandler.ashx" />

Note: Some time ASP.Net caches the image, so you may need to pass some GUID as querystring in the Handler.

Update: Sometime we may need to refresh the Captcha image, without post back, here is a simple javascript which will refresh the captcha image without post back.

<script type="text/javascript">
        function RefreshCaptcha() {
            var img = document.getElementById("imgCaptcha");
            img.src = "Handler.ashx?query=" + Math.random();
        }
</script>
<div>
<img src="Handler.ashx" id="imgCaptcha" />
<a href="#" onclick="javascript:RefreshCaptcha();">Refresh</a>
</div>

Here is the screenshot of web page using Captcha.

Captcha - Security Image using ASP.Net and C#

Captcha - Security Image using ASP.Net and C#