Silverlight 4.0 and Network Authentication while performing Web Request

Posted by: Mahesh Sabnis , on 7/24/2010, in Category Silverlight 2, 3, 4 and 5
Views: 35288
Abstract: In this article, I will demonstrate how to make a Web request to an external service using the Network Authentication feature . This mechanism helps making call to external services from the Silverlight 4.0 client by using the credentials, as demanded by the service.
When you develop Line-of-Business (LOB) applications using Silverlight, many a times you need to make a call to a WCF service and retrieve data from it. Now this service can be a WCF REST service and to make call to this service; the credential information required to send to the service might be different from the credentials of the logged in user. So in this case, to send request to the WCF service from Silverlight 4.0 client, you need to use the ‘WebClient’ class.
Note: With Silverlight 4.0, the WebClient class has provided a new property named ‘UseDefaultCredentials’. This property takes default credential of the current logged in user and makes a call to service.
In this article, I will demonstrate how to make a Web request to an external service using the Network Authentication feature. We will use credentials which are different from those of the current logged in user. I have used a WCF REST Service, hosted on IIS 7.0.
 
Creating WCF REST Service Hosted in IIS 7.0
 
Step 1: Open VS2010 and create a blank solution, name it as ‘SILV40_DemoNetwork_Auth_web_Request’.
Step 2: To this solution, add a new WCF Service Application project and name it as ‘WCF_SecureService’. Rename ‘IService1.cs’ to ‘IService’ and ‘Service1.svc’ to ‘Service1.svc’
Step 3: Open ‘IService.cs’ and write the following code:
C#
using System.ServiceModel;
using System.ServiceModel.Web;
 
namespace WCF_SecureService
{
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebGet]
        string[] GetNames();
    }
}
 
VB.NET
Imports System.ServiceModel
Imports System.ServiceModel.Web
 
Namespace WCF_SecureService
      <ServiceContract>
      Public Interface IService
            <OperationContract, WebGet>
            Function GetNames() As String()
      End Interface
End Namespace
 
The above contract defines [WebGet] attribute for WCF REST.
Step 4: Open Service.Svc.cs and implement the ‘IService’ interface in it.
C#
 
namespace WCF_SecureService
{
    public class Service : IService
    {
        public string[] GetNames()
        {
            return new string[] { "Ajay", "Rakesh", "Vinod" };
        }
    }
}
 
VB.NET
 
Namespace WCF_SecureService
      Public Class Service
            Implements IService
            Public Function GetNames() As String()
                  Return New String() { "Ajay", "Rakesh", "Vinod" }
            End Function
      End Class
End Namespace
 
Step 5: Write the following code in the Web.Config file:
<?xml version="1.0"?>
<configuration>
 <system.web>
    <compilation debug="true" targetFramework="4.0" />
 </system.web>
 <system.serviceModel>
    <services>
      <service name="WCF_SecureService.Service"
               behaviorConfiguration="ServBehave">
        <endpoint
           address=""
            binding="webHttpBinding"
            bindingConfiguration="basicSecureBindiingConfig"
            contract="WCF_SecureService.IService"/>
      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding name="basicSecureBindiingConfig">
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Windows"
                       proxyCredentialType="Windows">
            </transport>
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServBehave">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
          <serviceCredentials>
            <windowsAuthentication allowAnonymousLogons="False" includeWindowsGroups="True"/>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
 </system.serviceModel>
</configuration>
 
The above configuration shows that WCF service requires Windows Credential from the client application.
Step 6: Right click on Service.Svc and select ‘View Markup’ and write the following hosting code:
<%@ ServiceHost Language="C#" Debug="true"
Service="WCF_SecureService.Service" CodeBehind="Service.svc.cs"
Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
 
Step 7: Publish the service on IIS and test it.
 
Creating Silverlight Client Application.
 
Step 1: To the same solution, add a new Silverlight Application and name it as ‘SILV4_NetworkClientAuthentication’.
Note: Make sure that you select <New Web Project> for hosting the Silverlight Application in a new or Existing web site in solution.
Step 2: In the ‘MainPage.xaml’ write the following Xaml code:
<Grid x:Name="LayoutRoot" Background="White" Width="569">
        <Button Content="Get Names"
                Height="23" HorizontalAlignment="Left"
                Margin="88,60,0,0" Name="btnGetNames" VerticalAlignment="Top"
                Width="348" Click="btnGetNames_Click"/>
        <TextBox Height="200" HorizontalAlignment="Left" Margin="27,92,0,0" Name="txtdata" VerticalAlignment="Top" Width="502" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible" TextWrapping="Wrap" />
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="29,21,0,0" Name="textBlock1" Text="User Name:" VerticalAlignment="Top" Width="91" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="123,22,0,0" Name="txtUname" VerticalAlignment="Top" Width="120" />
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="269,21,0,0" Name="textBlock2" Text="Password:" VerticalAlignment="Top" Width="86" />
        <PasswordBox Height="23" HorizontalAlignment="Left" Margin="382,21,0,0" Name="txtPassword" VerticalAlignment="Top" Width="120" />
</Grid>
 
Step 3: Since I am using Silverlight child window for displaying an exception message, add a new Silverlight child window in the Silverlight project and name it as ‘ExceptionWindow.xaml’. Add a new TextBlock element in it as shown below:
<TextBlock Height="206" HorizontalAlignment="Left" Margin="23,9,0,0" Name="txtMessage" Text="TextBlock" VerticalAlignment="Top" Width="331" TextWrapping="Wrap" />
 
Step 4: Change the Constructor of the ‘ExceptionWindow’ class as shown below:
C#
public ExceptionWindow(string msg)
        {
            InitializeComponent();
            txtMessage.Text = msg;
        }
 
VB.NET
Public Sub New(ByVal msg As String)
                  InitializeComponent()
                  txtMessage.Text = msg
End Sub
Step 5: Now open ‘MainWindow.xaml.cs’ and write the following code in the ‘Click’ event of the GetNames button:
C#
private void btnGetNames_Click(object sender, RoutedEventArgs e)
        {
            WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp);
 
            WebClient wc = new WebClient();
            
            wc.Credentials = new NetworkCredential(txtUname.Text, txtPassword.Password);
            wc.UseDefaultCredentials = false;
 
            wc.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
 
            wc.DownloadStringAsync(new Uri("http://localhost:8900/SILV40_WCF_Nw_Auth/Service.svc/GetNames")); 
        }
 
        void wc_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null)
                {
                    txtdata.Text = e.Result;
                }
            }
            catch (Exception ex)
            {
                ExceptionWindow exWind = new ExceptionWindow(ex.Message + "There is a Problem is request, Please check User Name or Password");
                exWind.Show();
            }
        }
 
 
VB.NET
Private Sub btnGetNames_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
                  WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp)
 
                  Dim wc As New WebClient()
 
                  wc.Credentials = New NetworkCredential(txtUname.Text, txtPassword.Password)
                  wc.UseDefaultCredentials = False
 
                  AddHandler wc.DownloadStringCompleted, AddressOf wc_DownloadStringCompleted
 
                  wc.DownloadStringAsync(New Uri("http://localhost:8900/SILV40_WCF_Nw_Auth/Service.svc/GetNames"))
End Sub
 
Private Sub wc_DownloadStringCompleted(ByVal sender As Object, ByVal e As System.Net.DownloadStringCompletedEventArgs)
                  Try
                        If e.Result IsNot Nothing Then
                              txtdata.Text = e.Result
                        End If
                  Catch ex As Exception
                        Dim exWind As New ExceptionWindow(ex.Message & "There is a Problem is request, Please check User Name or Password")
                        exWind.Show()
                  End Try
End Sub
 
The above code shows that before making call to the service, prefix is registered to make use of ClientHttp network stack. The property ‘UseDefaultCredentials’ is set to false so that client can use a different User Name and Password to make a call, rather than using the credentials of the current logged in user.
Step 6: Now the important part here is we need to configure the Silverlight Application to use ‘Elevated Trust when running out-of-Box Application’. Right click on the application and select properties. Check enable running application out of browser as shown below:
Enable
Step 7: Click on the ‘Out of Browser Settings..’ button and check the check box for elevated rights as shown below:
BrowserSetting
Step 8: Run the application and enter username and password. After clicking on the button, if the credentials are accurate, then the data will be displayed in the textbox as shown below:
SILV4
If the Username or password is not correct then following result will be displayed:
Network
Conclusion: The new feature provided in Silverlight 4.0 helps the end user to make use of custom credentials required for the service; instead of using the credentials of the logged in user. This mechanism helps in making call to external services from the Silverlight 4.0 client by using credentials, as demanded by the service.       
The entire source code of this article can be downloaded over here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce the The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and the C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook