Authenticate .NET web service using custom SOAP header

Introduction

Using this method we simply add a required SOAP header to our web services calls.

We embed the SOAP header into our message and validate its contents on the server.

If the SOAP header validation done successfully, the web server sends the web service response to the consumer.

Pretty simple, right?

Using the code

First we had our service declaration:

/// <summary>
/// Summary description for SOAPHeaderService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(Name = "TestService",ConformsTo = WsiProfiles.BasicProfile1_1)]
public class SOAPHeaderService : System.Web.Services.WebService
{
    // Visual studio will append a "UserCredentialsValue" property to the proxy class
    public UserCredentials consumer;

    public SOAPHeaderService()
    {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

Notice that the “WebServiceBinding” attribute has the “Name” argument set to “TestService”, I’ll explain this later.

Now, I write the custom SOAP header that I want to include in the SOAP message.

To do this I’ll create a class inherited from “System.Web.Services.Protocols.SoapHeader” , and I’ll but the required properties in it.

public class UserCredentials : System.Web.Services.Protocols.SoapHeader
{
    public string userName;
    public string password;
}

Let’s add instance from that header in our service

// Visual studio will append a "UserCredentialsValue" property to the proxy class
    public UserCredentials consumer;

Note that the visual studio will create a property in web service proxy called “UserCredentialsValue” which will map the “consumer” public property in the web service.

Now we had to write a “Web Method” that uses that header in messaging.

[WebMethod]
    [SoapDocumentMethod(Binding = "TestService")]
    [SoapHeader("consumer",Required=true)]
    public string GetBalance()
    {
        if (checkConsumer())
            return consumer.userName + " had 10000000 credit";
        else
            return "Error in authentication";
    }

Note that I have added the “Binding” value to that I had used in declaring my service.

Also I declared the SOAP header that method will require when called, as long as declaring it with required.

Now, the only thing is remaining is to call the service with the SOAP header:

SOAPHeaderService.SOAPHeaderService service = new SOAPHeaderService.SOAPHeaderService();
SOAPHeaderService.UserCredentials user = new SOAPHeaderService.UserCredentials();

user.userName = "Ahmed";
user.password = "1234";

service.UserCredentialsValue = user;

Console.WriteLine(service.GetBalance());

We just get reference to the service and the SOAP header, assign the SOAP header properties, attach it with the SOAP message and then make our call to the web method.

This is the console result after calling the service with username = “Ahmed” and password = “1234”

image

This one with other data

image

Securing their web services is a thing that many developers ignore while they are working; they relay that on that is a difficult and nasty task.

In the fact securing web service is all about understand the messaging layer and the protocols, you just need to go a little more deep and then you will find it is a very simple task.

Sample Project

I hope that helped

Ahmed

Rule based security using Microsoft Enterprise Library and CAS

Introduction

Rule based security is a very effective way to authorize your code, and code access security is a clean, easy to use and effective way to handle the security validation.

The Enterprise Library Security Application Block provides a configurable way to handle Rule based security.

In this article I’ll explain a solution to secure web applications using custom membership and role providers with the Enterprise Library Security Application Block and code access security.

You need the Enterprise Library installed.

Using the code

First, we need to implement our custom membership provider, in this example I’ll just use static code to explain the provider [Not going to the database or anything].

For this sample I just need to implement the following method:

public override bool ValidateUser(string username, string password)
        {
            return true;
        }

Then, we need to implement our custom role provider.

I just need the following to implement methods:

public override string[] GetRolesForUser(string username)
{
            return SecurityProvider.GetRolesForUser(username);}

public override bool IsUserInRole(string username, string roleName)
{
            return SecurityProvider.IsUserInRule(HttpContext.Current.User, roleName);}

Sure, you can build your own providers with a custom database.

Now, Let’s have a look on the [SecurityProvider] class:

public class SecurityProvider{
        public static bool IsUserInRule(IPrincipal principal, string ruleName)
        {
            IAuthorizationProvider authorizationProvider = AuthorizationFactory.GetAuthorizationProvider();
            return authorizationProvider.Authorize(principal, ruleName);
        }

        public static string[] GetRolesForUser(string username)
        {
            switch (username.ToLower())
            {
                case ("admin"):
                    return new string[] { "Admin" };

                case ("manager"):
                    return new string[] { "Manager" };

                case ("user"):
                    return new string[] { "User" };

                default:
                    return new string[] { "" };

            }
        }
    }

I use the Enterprise Library Security Application Block to make the validation on the rules from the configuration file.

Then, we need to implement a custom CAS permission and attribute like the following [Not implemented functions removed from the next code section but is available in the source code]

public class RulesSecurityPermission : IPermission
    {

        private string _rule;
        public string Rule
        {
            get
            {
                return this._rule;
            }
            set
            {
                this._rule = value;
            }
        }

        public RulesSecurityPermission(string roleName)
        {
            _rule = roleName;
        }

        void IPermission.Demand()
        {
            if (!SecurityProvider.IsUserInRule(Thread.CurrentPrincipal, Rule))
                throw new SecurityException();
        }
    }
public class RulesSecurityPermissionAttribute : CodeAccessSecurityAttribute
    {
        public RulesSecurityPermissionAttribute(SecurityAction action)
            : base(action)
        {
            
        }

        public override IPermission CreatePermission()
        {
            return new RulesSecurityPermission(Rule);
        }
        
        private string _role;
        public string Rule
        {
            get
            {
                return this._role;
            }
            set
            {
                this._role = value;
            }
        }
    }

Now, let’s have a look on the configurations file:

<configuration>
  <configSections>
    <section name="securityConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Security.Configuration.SecuritySettings, Microsoft.Practices.EnterpriseLibrary.Security, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </configSections>
  <securityConfiguration defaultAuthorizationInstance="RuleProvider" defaultSecurityCacheInstance="">
    <authorizationProviders>
      <add type="Microsoft.Practices.EnterpriseLibrary.Security.AuthorizationRuleProvider, Microsoft.Practices.EnterpriseLibrary.Security, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        name="RuleProvider">
        <rules>
          <add expression="R:Admin" name="Administratoin" />
          <add expression="R:Admin OR R:Manager" name="Management" />
          <add expression="R:Manager OR R:User" name="Usage" />
        </rules>
      </add>
    </authorizationProviders>
  </securityConfiguration>

  <system.web>
    
    <compilation debug="true" />
    
    <authentication mode="Forms">
      <forms loginUrl="~/Login.aspx" defaultUrl="~/Default.aspx">
      </forms>
    </authentication>
    
    <authorization>
      <deny users="?"/>
    </authorization>
    
    <membership defaultProvider="CustomMembershipProvider">
      <providers>
        <clear/>
        <add name="CustomMembershipProvider" type="Shokr.Security.RuleBasedSecurity.CustomMembershipProvider"/>
      </providers>
    </membership>
    
    <roleManager defaultProvider="CustomRolesProvider" enabled="true">
      <providers>
        <clear/>
        <add name="CustomRolesProvider" type="Shokr.Security.RuleBasedSecurity.CustomRolesProvider" />
      </providers>
    </roleManager>
    
    </system.web>
</configuration>

In the above code, I had registered the [AuthorizationRuleProvider] from the Enterprise Library and configured our custom membership and roles providers.

Finally, this is the sample in action:

Navigate to the login page, and login with [admin] and any password.

image

You will be redirected to the default page:

image

Click on [Administrative function], you will see that the method executed successfully

image

Click on [User function], you will see security error:

image

Sample project

I hope that helped

Ahmed

Silverlight Stock Rates Rotator

Introduction

Silverlight is a rich framework that works in web browsers using a browser plug-in, just like Flash, but with it, you can interact more easily with .NET libraries. Silverlight has the same code-behind model that exists in ASP.NET, and operates under a modified light version from the .NET framework. With Silverlight, you can build Flash-like applications with full .NET server side code integration. Now, I’ll go through how to build a stock rates rotator with Silverlight and embed it into an ASPX page, step by step. First, you have to download the Silverlight Tools Beta 2 For Visual Studio 2008.

Using the code

Open Visual Studio 2008, and open a new project, select the Silverlight node under Visual C#, and select Silverlight Application:

NewProject

Click OK to proceed to the following screen:

SelectWeb

Select the first option to add a new web site to test your Silverlight controls, and click OK.

Solution

Notice these files in you solution:

  • App.xaml: The entry point for your application that tells which control to begin with, and within it, you can declare the shared variables.
  • Page.xaml: A Silverlight control which will hold the XAML and has a code-behind file “Page.xaml.cs” which holds the server side code.

Now, I’ll start developing the email form in “Page.xaml”:

<canvas xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns="http://schemas.microsoft.com/client/2007">
        <canvas.triggers>
            <eventtrigger routedevent="Canvas.Loaded">
                <beginstoryboard>
                    <storyboard repeatbehavior="Forever"
                           storyboard.targetproperty="(Canvas.Left)" x:name="animation">
                        <doubleanimation duration="0:0:10" to="-820"
                               from="0" storyboard.targetname="txtResult">
                    </doubleanimation>
                </storyboard>
            </beginstoryboard>
        </eventtrigger>
        <border opacity="1" background="Red">
            <textblock text=" Updating stock rates ...... please wait "
                       foreground="Wheat" x:name="txtLoading" />
        </border>
        <textblock x:name="txtResult">
</textblock></canvas.triggers></canvas>

I made the animation to rotate the “txtResult” textblock from right to left forever. This is a very simple animation; also, I added another textblock to simulate the loading effect. Now, I’ll code the web service which will provide the stock rates to the Silverlight control.

[WebMethod]
public string GetStockData()
{
    // Just to see the loading effect
    System.Threading.Thread.Sleep(2000);

    StringBuilder stockData = new StringBuilder();
    Random randomRate = new Random();

    stockData.Append("USD " + randomRate.NextDouble() + "   |   ");
    stockData.Append("KD " + randomRate.NextDouble() + "   |   ");
    stockData.Append("GBP " + randomRate.NextDouble() + "   |   ");
    stockData.Append("EGP " + randomRate.NextDouble() + "   |   ");
    stockData.Append("AUD " + randomRate.NextDouble());

    return stockData.ToString();
}

It’s a very simple web method just to return the required string. Now, we must code calling the web service from the Silverlight control.

public partial class Page : UserControl
{
    # region "Public members"
    DispatcherTimer timer;
    BasicHttpBinding bind;
    EndpointAddress endPoint;
    // Change this to your local URL
    const string WebServiceUrl =
      "http://localhost:11545/StockRotatorWeb/services/StockData.asmx";
    WebServices.StockDataSoapClient stockService;
    # endregion

    public Page()
    {
        InitializeComponent();

        // Initialize timer
        timer = new DispatcherTimer();
        timer.Interval = new TimeSpan(0, 0, 10);
        timer.Tick += new EventHandler(timer_Tick);
        // Initialize the web service proxy and add the event handler
        bind = new BasicHttpBinding();
        endPoint = new EndpointAddress(WebServiceUrl);
        stockService = new WebServices.StockDataSoapClient(bind, endPoint);
        stockService.GetStockDataCompleted += new
          EventHandler<stockrotator.webservices.getstockdatacompletedeventargs>(
          stockService_GetStockDataCompleted);
        stockService.GetStockDataAsync();
        // Start the timer
        timer.Start();
    }
    // Invoked when the calling completed or timed out
    void stockService_GetStockDataCompleted(object sender,
         StockRotator.WebServices.GetStockDataCompletedEventArgs e)
    {
        try
        {
            // Update the result
            txtResult.Visibility = Visibility.Visible;
            txtResult.Text = e.Result.ToString();
        }
        catch (Exception ex)
        {
            // Display the error
            txtResult.Text = ex.InnerException.Message;
        }
        finally
        {
            // Hide the loading textbloxk and restart the timer
            txtLoading.Visibility = Visibility.Collapsed;
            timer.Start();
        }
    }

    void timer_Tick(object sender, EventArgs e)
    {
        timer.Stop();
        txtLoading.Visibility = Visibility.Visible;
        txtResult.Visibility = Visibility.Collapsed;
        // Make the async call to the web service
        stockService.GetStockDataAsync();
    }
}

And this is the test page in action:

Loading....

And, this with the data displayed:

Loaded

Sample project

I hope that helped

Ahmed

Slide menu using jQuery

Introduction

jQuery is a fast, concise, JavaScript library that simplifies how you traverse HTML documents, handle events, perform animations, and add AJAX interactions to your web pages. jQuery is designed to change the way that you write JavaScript.

In this article, I’ll build a sliding JavaScript menu using jQuery.

Using the code

First, you must reference the jQuery library which can be downloaded form here. Then, you can make the menu HTML page as in the following code:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>JQuery Sample Menu</title>
    <link rel="Stylesheet" type="text/css" href="styles/navigation.css" />
    <script type="text/javascript" language="javascript" src="scripts/jquery-1.2.3.js"/>
    <script type="text/javascript" language="javascript" src="scripts/CustomMenu.js"/>
</head>
<body>
<h2>This is a sample menu using JQuery</h2>
<h4>Try to click on the clickable items in the menu to see the animation</h4>
<ul class="menu">
    <li>- Parent item with no children</li>
    <li>
    - Item 1 with children
    <ul >
    <li>Nested item 1</li>
    <li>Nested item 2</li>
    </ul>
    </li>
    <li>
    - Item 2 with children
    <ul >
    <li>Nested item 1</li>
    <li>Nested item 2</li>
    <li>Nested item 3</li>
    <li>Nested item 4</li>
    </ul>
    </li>
    <li>
    - Item 3 with children
    <ul>
    <li>Nested item 1</li>
    <li>Nested item 2</li>
    <li>Nested item 3</li></ul>
    </li>
    </ul>
</body>
</html>

Now, for the JavaScript magic! Just use the following JavaScript piece of code:

$(function() // Register the menu
      {
// Add the click event handler on the list item with sub list
$('li:has(ul)') 
           .click(function(event){
            if (this == event.target) {
               // Hide all the children of the other lists
               $('li:has(ul)').children().hide('slow'); 
               // Make the animation
               $(this).children().animate({opacity:'toggle',height:'toggle'},'slow'); 
                                      }
                     return false;
                                 }
                   )
            // Change the cusrsor.
           .css({cursor:'pointer'})
           // Hide all the nested lists (on the first tinm only).
           .children().hide();
       }
 );

Now you can have the sliding effect without so much JavaScript coding.

Menu at start:

init

Menu in action:

loading

Sample project

I hope that helped

Ahmed