Wednesday, February 15, 2012

Web Service or WCF authertication using Soap header

1. This is how do we authenticate web service for secure data exchange;It is done using Soap Header.we have to set username and password here in soap header.

Use the code like in web service:


using System;
using System.Collections;
using System.Data;
using System.ComponentModel;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;


/// <summary>
/// Summary description for WebService
/// </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 WebService : System.Web.Services.WebService
{
    public class AuthHeader : SoapHeader
    {
        public string Username;
        public string Password;
    }

    public AuthHeader Authentication;
    [SoapHeader("Authentication", Required = true)]
    [WebMethod(Description = "Returns some sample data")]
    public DataSet SensitiveData()
    {
        DataSet data = new DataSet();

        //Do our authentication
        //this can be via a database or whatever
        if (Authentication.Username == "test" && Authentication.Password == "test")
        {
            //they are allowed access to our sensitive data

            //just create some dummy data
            DataTable dtTable1 = new DataTable();
            DataColumn drCol1 = new DataColumn("Data", System.Type.GetType("System.String"));
            dtTable1.Columns.Add(drCol1);

            DataRow drRow = dtTable1.NewRow();
            drRow["Data"] = "Sensitive Data";
            dtTable1.Rows.Add(drRow);
            dtTable1.AcceptChanges();

            data.Tables.Add(dtTable1);



        }
        else
        {
            data = null;
        }

        return data;
    }
   

}


2.Now in client application refer the web service and create its object and then pass username and password as required by web service and authenticated then data will return otherwise nothing will return.

code is as follows:


 protected void Page_Load(object sender, EventArgs e)
        {
            //simple client page
            AuthWebService.WebService webService = new AuthWebService.WebService();
            AuthWebService.AuthHeader authentication = new AuthWebService.AuthHeader();
            authentication.Username = "test";
            authentication.Password = "test";
            webService.AuthHeaderValue = authentication;
            DataSet ds = new DataSet();
            ds = webService.SensitiveData();
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }


Now run and enjoyee web service authentication and same way we can do for WCf....



No comments:

Post a Comment