How to: Specify Client Credentials for a Data Service Request (WCF Data Services/Silverlight)

You can specify the credentials that are used when making a request to a data service that implements the Open Data Protocol (OData). To do this, you must be making a cross-domain request, be running out of the browser, or you must explicitly set the value of the HttpStack property to ClientHttp. In these cases, the default credentials from the credential cache are used. You can also supply non-default credentials by setting the UseDefaultCredentials property to false and supplying a NetworkCredential for the Credentials property of the DataServiceContext. The example in this topic shows how to explicitly provide credentials that are used by the Silverlight client when requesting data from the data service.

The Northwind sample data service accessed by the application is created when you complete the procedures in the topic How to: Create the Northwind Data Service (WCF Data Services/Silverlight). You can also use the Northwind sample data service that is published on the OData Web site; this sample data service is read-only and attempting to save changes returns an error. The sample data services on the OData Web site allow anonymous authentication.

The following example is from the code-behind page for an Extensible Application Markup Language (XAML) file that is the main page of the Silverlight application. This example displays a LoginWindow instance to collect authentication credentials from the user, and then uses these non-default credentials when making a request to the data service by using the Silverlight client HTTP implementation.

Imports ClientCredentials.Northwind
Imports System.Data.Services.Client
Imports System.Windows.Data
Imports System.Net

Partial Public Class MainPage
    Inherits UserControl

    ' Create the binding collections and the data service context.
    Private binding As DataServiceCollection(Of Customer)
    Private context As NorthwindEntities
    Private customerAddressViewSource As CollectionViewSource

    ' Instantiate the service URI and credentials.
    Dim serviceUri As Uri = New Uri("http://localhost:54321/Northwind.svc/")
    Private credentials As NetworkCredential = New NetworkCredential()

    Public Sub Main()
    End Sub

    Private Sub MainPage_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)

        ' Get credentials for authentication.
        Dim login As LoginWindow = New LoginWindow()
        AddHandler login.Closed, AddressOf loginWindow_Closed
    End Sub

    Private Sub loginWindow_Closed(ByVal sender As Object, ByVal e As EventArgs)
        Dim userName = String.Empty
        Dim domain = String.Empty
        Dim password = String.Empty

        ' Get back the LoginWindow instance.
        Dim login As LoginWindow = CType(sender, LoginWindow)

        If login.DialogResult = True AndAlso Not login.userNameBox.Text Is String.Empty Then

            ' Instantiate the binding collection.
            binding = New DataServiceCollection(Of Customer)()

            ' Instantiate the context.
            context = New NorthwindEntities(serviceUri)

            ' Register the LoadCompleted event for the binding collection.
            AddHandler binding.LoadCompleted, AddressOf binding_LoadCompleted

            ' Define an anonymous LINQ query that returns a collection of Customer types.
            Dim query = From c In context.Customers
                        Where c.Country = "Germany"
                        Select c

            ' Get the user name and domain from the login.
            Dim qualifiedUserName As String() = login.userNameBox.Text.Split(New [Char]() {"\"c})
            If qualifiedUserName.Length = 2 Then
                domain = qualifiedUserName(0)
                userName = qualifiedUserName(1)
                userName = login.userNameBox.Text
            End If
            password = login.passwordBox.Password

            ' Select the client HTTP stack and set the credentials.
            context.HttpStack = HttpStack.ClientHttp
            context.UseDefaultCredentials = False
            context.Credentials = _
                New NetworkCredential(userName, password, domain)

                ' Execute the query asynchronously.
            Catch ex As Exception
                Dim cw = New ChildWindow()
                cw.Content = ex.Message
            End Try
        ElseIf login.DialogResult = False Then        
            Dim cw = New ChildWindow()
            cw.Content = "Login cancelled."
        End If
    End Sub
    Private Sub binding_LoadCompleted(ByVal sender As Object, ByVal e As LoadCompletedEventArgs)
        If e.Error Is Nothing Then
            serviceUriLabel.Content = serviceUri.ToString()

            ' Load all pages of Customers before binding.
            If Not binding.Continuation Is Nothing Then
                ' Load your data here and assign the result to the CollectionViewSource.
                customerAddressViewSource = _
                    CType(Me.Resources("customerViewSource"), CollectionViewSource)
                customerAddressViewSource.Source = binding
            End If

            ' Display the error message from the data service.
            Dim cw = New ChildWindow()
            cw.Content = e.Error.Message
        End If
    End Sub
End Class

The following XAML defines the main page of the Silverlight application.

    <UserControl x:Class="ClientCredentials.MainPage"
    d:DesignHeight="312" d:DesignWidth="577" 
             xmlns:my="clr-namespace:ClientCredentials" Loaded="MainPage_Loaded">
        <CollectionViewSource x:Key="customerViewSource" 
                              d:DesignSource="{d:DesignInstance my:Northwind.Customer, CreateList=True}" />
    <Grid x:Name="LayoutRoot" Background="White" DataContext="" Height="312" Width="577"
          VerticalAlignment="Top" HorizontalAlignment="Left">
            <RowDefinition Height="203*" />
            <RowDefinition Height="119*" />
            <ColumnDefinition Width="336*" />
        <sdk:DataGrid AutoGenerateColumns="False" Height="213" HorizontalAlignment="Left" 
                      ItemsSource="{Binding Source={StaticResource customerViewSource}}" 
                      Name="customerDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" 
                      VerticalAlignment="Top" Width="553" Margin="12,44,0,0" 
                      Grid.RowSpan="2" Grid.ColumnSpan="1">
                <sdk:DataGridTextColumn x:Name="customerIDColumn" Binding="{Binding Path=CustomerID}" 
                                        Header="Customer" Width="80" />
                <sdk:DataGridTextColumn x:Name="addressColumn" Binding="{Binding Path=Address}" 
                                        Header="Address" Width="180" />
                <sdk:DataGridTextColumn x:Name="cityColumn" Binding="{Binding Path=City}" 
                                        Header="City" Width="120" />
                <sdk:DataGridTextColumn x:Name="countryColumn" Binding="{Binding Path=Country}" 
                                        Header="Country" Width="80" />
                <sdk:DataGridTextColumn x:Name="postalCodeColumn" Binding="{Binding Path=PostalCode}" 
                                        Header="Postal Code" Width="90" />
                <sdk:DataGridTextColumn Binding="{Binding Path=CompanyName}" Header="CompanyName" />
                <sdk:DataGridTextColumn Binding="{Binding Path=ContactName}" Header="ContactName" />
                <sdk:DataGridTextColumn Binding="{Binding Path=Phone}" Header="Phone" />
        <sdk:Label Grid.Row="0" Grid.Column="0" Height="26" HorizontalAlignment="Left" Margin="16,12,0,0" 
                   Name="serviceUriLabel" VerticalAlignment="Top" Width="550"  />

The following example is from the code-behind page for the ChildWindow that is used to collect the authentication credentials from the user before making a request to the data service.

Imports System.ComponentModel

Partial Public Class LoginWindow
    Inherits ChildWindow

    Public Sub New()
    End Sub

    Private Sub OKButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles OKButton.Click
        Me.DialogResult = True
    End Sub

    Private Sub CancelButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles CancelButton.Click
        Me.DialogResult = False
    End Sub

    Private Sub LoginWindow_Closing(ByVal sender As System.Object, ByVal e As CancelEventArgs)
        If Me.DialogResult = True AndAlso _
                    (Me.userNameBox.Text = String.Empty OrElse Me.passwordBox.Password = String.Empty) Then
            e.Cancel = True
            Dim cw As ChildWindow = New ChildWindow()
            cw.Content = "Please enter name and password or click Cancel."
        End If
    End Sub
End Class

The following XAML defines the login window that is a ChildWindow of the Silverlight application.

    <controls:ChildWindow x:Class="ClientCredentials.LoginWindow"
           Width="400" Height="200" 
           Title="LoginWindow" xmlns:sdk="" Closing="LoginWindow_Closing">
    <StackPanel Name="LayoutRoot" Orientation="Vertical" VerticalAlignment="Top">
        <StackPanel Orientation="Horizontal">
            <TextBlock Height="25" HorizontalAlignment="Left" Margin="10,20,0,0" Name="userNameLabel" VerticalAlignment="Top" 
                       Width="80" Text="User name:"/>
            <TextBox Height="23" HorizontalAlignment="Left" Margin="10,20,0,0"  Name="userNameBox" VerticalAlignment="Top" 
                     Width="150" Text="DOMAIN\login"/>
        <StackPanel Orientation="Horizontal" VerticalAlignment="Top">
            <TextBlock Height="25" HorizontalAlignment="Left" Margin="10,20,0,0" Name="pwdLabel" Width="80" Text="Password:"/>
            <PasswordBox Height="23" HorizontalAlignment="Left" Margin="10,20,0,0" Name="passwordBox" Width="150" />
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Height="80" VerticalAlignment="Top">
            <Button x:Name="CancelButton" Content="Cancel" Click="CancelButton_Click" Width="75" Height="23" 
                HorizontalAlignment="Right" Margin="8" />
            <Button x:Name="OKButton" Content="OK" Click="OKButton_Click" Width="75" Height="23" 
                HorizontalAlignment="Right" Margin="8" />

The following security considerations apply to the example in this topic:

  • To verify that the credentials supplied in this sample work, the Northwind data service must use an authentication scheme other than anonymous access. Otherwise, the Web site hosting the data service will not request credentials.

  • User credentials should only be requested during execution and should not be cached. Credentials must always be stored securely.

  • Data sent with Basic and Digest Authentication is not encrypted, so the data can be seen by an adversary. Additionally, Basic Authentication credentials (user name and password) are sent in cleartext and can be intercepted.

Community Additions