google analytics

Wednesday, November 5, 2008

ASP.NET Form Authentication

Hello All

Today I will demonstrate how to do Form based authentication manually.Though it can be maintained through login controls which is provided by Visual Studio but sometime we need to do the task without using those controls and the required database.

First we have to perform validation for the user, then we needed to authenticate the user for different type of task according to the role of the user ( I will do role based authentication.) In my example I have a folder named "Secure" which can be access only by the Admin user. (in the following code I assume that U have done the validation for a user.)

  /* we are taking expire time duration form application settings file you may also hard coded this value.*/
double EXPIRETIMELIMIT = Convert.ToDouble(ConfigurationManager.AppSettings["EXPIRETIMELIMIT"]);

  FormsAuthentication.Initialize();
  FormsAuthentication.HashPasswordForStoringInConfigFile("password", "md5");
            
  StringBuilder roles = newStringBuilder();
  /* bellow i have added 2 roles , you may add roles according to your logic.*/
  roles.Append("Admin");
  roles.Append("Manager");
               
  FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "User Name", DateTime.Now, DateTime.Now.AddMinutes(EXPIRETIMELIMIT), true, roles.ToString(), FormsAuthentication.FormsCookiePath);         
  string hash = FormsAuthentication.Encrypt(ticket);      
  HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
/*We have to set the cookie expire time manually,its not working which we set in the parameter  of the FormsAuthenticationTicket's constructor .*/
 cookie.Expires = DateTime.Now.AddMinutes(EXPIRETIMELIMIT); 

 if(ticket.IsPersistent)
    cookie.Expires = ticket.Expiration;

 Response.Cookies.Add(cookie);

 Response.Redirect("Admin/Home.aspx");
Now open the the Global.asax file,if its not exist in your current solution add it as a new item. Then add the following code block as bellow,which will chek the authentication in each page request.
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
   {
       if (HttpContext.Current.User != null)
       {
           if (HttpContext.Current.User.Identity.IsAuthenticated)
           {
               if (HttpContext.Current.User.Identity is FormsIdentity)
               {
                   FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;

                   FormsAuthenticationTicket ticket = identity.Ticket;
//         UserData is the roles which we have assigned before.
                   string[] roles = ticket.UserData.Split(new Char[] {','});
                                     
                   HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
                   
               }            
           }        
       }    
   }
Now its the time to securing our folder from web.config  . When any Authorized user will try to access in the Admin folder then this will check the "Admin" role for the user.
<authentication mode="Forms">
        <forms name="MYWEBAPP.ASPXAUTH"  loginUrl="TeleMarketerLogin.aspx" protection="All" path="/"/>  
    </authentication>
    <authorization>
        <deny users="?"/>
        <allow roles="Manager,Admin"/>
        <deny users="*"/>
    </authorization>

<location path="Secure">
    <system.web>
        <authorization>
        <deny users="?"/>
        <allow roles="Admin"/>
        <deny users="*"/>
        </authorization>
    </system.web>
</location>

<location path="App_Themes">
    <system.web>
        <authorization>
            <allow users="*"/>
        </authorization>
    </system.web>
</location>
thats all for today.
BYE
User ScrumPad for your Agile based projects.

Wednesday, October 22, 2008

Web service creation & consuming with ASP.NET

Hello all

Today I will show how to create web service with VS2008 and consume it in different application.
first I have opened a web service from File>New web site > web service named "DemoWebService".

now in the solution explorer we can a Service.asmx file and the Service.cs file in App_Code . I have added another web service named WebServiceTest.asmx so a WebServiceTest.cs file also added in App_Code folder.

we will basically work with *.cs file to make the service.
I opened the WebServiceTest.cs file and there is a demo web method named Hello World. So I will create another method named "GetValue" which will also return a string.

using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
/// <summary>
///
Summary description for WebServiceTest
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebServiceTest : System.Web.Services.WebService {
public WebServiceTest () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public string GetValue()
{
string valueString = "the result of your logic.";
return valueString;
}
}
We have to add the [WebMethod]  attribute before starting any method which will serve the web service.

Now i will add another web site named "ConsumeWebService" which will be used to consume the web service. and add web reference to the site as bellow.


for the simplicity I have chosen the Web service in this solution( you can choose you own type as you needed for the further use).
now we will see  our Class file which we have created in our web service, I have select the WebServiceTest for the implementing.  

Now we will sell our methods in the next window, now I have selected the web reference name as "WebserviceTest" and add the reference .

for the simplicity I will skip the  discussion of  *.disco & *.wsdl file,this file are basically needed for communication between our application and web service.

now I open the Default.aspx.cs file and add the WebServiceTest namespace and call the Method of web service as following.

no compile the web site and and enjoy the service.

BYE

Tuesday, October 21, 2008

Captcha generate with ASP.NET & C#

Hello all

Today I will demonstrate how to generate captcha with asp.net & C# . though there are many .NET plugin and controls to serve the purpose but my focus is to generate the a random image and its manipulation with the help of .NET framework.

First open a web project and add a "Web user control" , in the example the name of my control is "ImageGeneratorControl.ascx" . the purpose of the control is to generate a image according to the random character.

Now open the  "ImageGeneratorControl.ascx.cs" file (i used the code behind method for the example.) , to generate image we have to use System.Drawing base class.

firstly we have to make a Bitmap type object where the image will generate, then for the texture we have to take a Graphics type object and manipulate the our random string there, after that we will sat the content type and save the Bitmap object stream so that it may  generate a image file, finally we have to dispose our objects.

there is a method named "RandomString" which will take the length of sting to be generate as parameter, in the method i have generate a random number and convert the number into string.In an addition the string will be save in Session.

The code of the  "ImageGeneratorControl.ascx.cs" is as bellow :

using System;
using System.Drawing;

public partial class ImageGeneratorControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Bitmap objBmp = new Bitmap(100, 30);
        Graphics objGraphics ;
        Font objFont = new Font("Arial", 16, FontStyle.Bold);

        objGraphics = Graphics.FromImage(objBmp);
        objGraphics.Clear(Color.WhiteSmoke);

        objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        objGraphics.DrawString(this.RandomString(6), objFont, Brushes.Gray, 3, 3);

        Response.ContentType = "image/GIF";
        objBmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);

        objBmp.Dispose();
        objGraphics.Dispose();
        objFont.Dispose();
    }

    private string RandomString(int length)
    {
        Random rand = new Random();
        char ch;

        System.Text.StringBuilder randString = new System.Text.StringBuilder();

        for(int i = 0 ; i<length; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32((Math.Floor(rand.NextDouble() * 26) + 65)));
            randString.Append(ch);
        }
        Session["CaptchaString"] = randString.ToString().ToLower();
        return randString.ToString().ToLower();    
    }
}

now we have to place that control in a aspx page (we also can handle it with HTTPHandler but for the simplicity i have used a aspx page which will act as a "GIF" image)

so i have taken a Image.aspx file and register the Control as following:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Image.aspx.cs" Inherits="_Image" %>

<%@ Register src="ImageGeneratorControl.ascx" tagname="ImageGeneratorControl" tagprefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<head runat="server">

</head>
<body>
    <form id="form1" runat="server">
      <uc1:ImageGeneratorControl ID="ImageGeneratorControl1" runat="server" />                     
    </form>
</body>

Now this Image.aspx file will act as a Image . What we have to do now is include the Image.aspx page in our main aspx file where the image will be visible. i have used Container.aspx file to generate the captcha as following:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Container.aspx.cs" Inherits="Container" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Captcha Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div><img src="Image.aspx" /></div>
    </form>
</body>
</html>

now you can protect the form from spamming according to your logic,session and image data. 

BYE