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: 36907
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:
using System.ServiceModel;
using System.ServiceModel.Web;
namespace WCF_SecureService
    public interface IService
        string[] GetNames();
Imports System.ServiceModel
Imports System.ServiceModel.Web
Namespace WCF_SecureService
      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.
namespace WCF_SecureService
    public class Service : IService
        public string[] GetNames()
            return new string[] { "Ajay", "Rakesh", "Vinod" };
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"?>
    <compilation debug="true" targetFramework="4.0" />
      <service name="WCF_SecureService.Service"
        <binding name="basicSecureBindiingConfig">
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Windows"
        <behavior name="ServBehave">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
            <windowsAuthentication allowAnonymousLogons="False" includeWindowsGroups="True"/>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
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" />
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:
public ExceptionWindow(string msg)
            txtMessage.Text = msg;
Public Sub New(ByVal msg As String)
                  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:
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)
                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");
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)
                        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")
                  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:
Step 7: Click on the ‘Out of Browser Settings..’ button and check the check box for elevated rights as shown below:
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:
If the Username or password is not correct then following result will be displayed:
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 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 Book 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 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+

Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades 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), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet or connect with him on LinkedIn

Page copy protected against web site content infringement 	by Copyscape

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