How to: Enable Authentication in Open Ria Services
[ This document was written for WCF Services Version 1 Service Pack 2 and might not be up to date Please see Release Notes or Changelog for a list of changes since WCF RIA Services ]
This topic demonstrates how to enable user authentication in your application by using Open Ria Services. It shows the code that you must add to both the server project and the client project to make authentication available as a service to the client application. You can restrict access to a domain operation to only authenticated users by applying the RequiresAuthenticationAttribute attribute to the domain operation.
Authentication in Open Ria Services builds upon the authentication framework in ASP.NET. For more information about ASP.NET authentication, see Introduction to Membership.

To configure the server project

  1. 1.
    In the server project, open the Web.config file.
  2. 2.
    In the \ element, add an \ element.
  3. 3.
    Set the mode property to the authentication mode that you will use in the project.
    The following code shows the \ element with mode set to Forms. Set the mode property to Windows to use Windows Authentication. Your Web.config file will contain other elements.
    1
    <system.web>
    2
    <authentication mode="Forms"></authentication>
    3
    </system.web>
    Copied!
  4. 4.
    Save the Web.config file.
  5. 5.
    In Solution Explorer, right-click the server project, select Add and then New Item.
    The Add New Item dialog box appears.
  6. 6.
    Select the Authentication Domain Service template and specify a name for the service.
    ​
    ​
  7. 7.
    Click Add.
  8. 8.
    To restrict access to a domain operation to only authenticated users, apply the RequiresAuthenticationAttribute attribute to the domain operation.
    The following example specifies that only authenticated users can access the GetSalesOrderHeaders method.
    1
    <RequiresAuthentication()> _
    2
    Public Function GetSalesOrderHeaders() As IQueryable(Of SalesOrderHeader)
    3
    Return Me.ObjectContext.SalesOrderHeaders
    4
    End Function
    Copied!
    1
    [RequiresAuthentication()]
    2
    public IQueryable<SalesOrderHeader> GetSalesOrderHeaders()
    3
    {
    4
    return this.ObjectContext.SalesOrderHeaders;
    5
    }
    Copied!
  9. 9.
    Build the solution.

To configure the authentication service on the client project

  1. 1.
    In the client project, open the code-behind file for the App.xaml file (App.xaml.cs or App.xaml.vb).
  2. 2.
    In the constructor, create an instance of the WebContext class.
  3. 3.
    Set the Authentication property to the type of authentication that you configured in the server project, and add the WebContext instance to the ApplicationLifetimeObjects.
    The following example shows how to set authentication to FormsAuthentication.
    1
    Public Sub New()
    2
    InitializeComponent()
    3
    ​
    4
    Dim webcontext As New WebContext
    5
    webcontext.Authentication = New OpenRiaServices.Client.Authentication.FormsAuthentication
    6
    Me.ApplicationLifetimeObjects.Add(webcontext)
    7
    End Sub
    Copied!
    1
    public App()
    2
    {
    3
    this.Startup += this.Application_Startup;
    4
    this.UnhandledException += this.Application_UnhandledException;
    5
    ​
    6
    InitializeComponent();
    7
    ​
    8
    WebContext webcontext = new WebContext();
    9
    webcontext.Authentication = new OpenRiaServices.Client.Authentication.FormsAuthentication();
    10
    this.ApplicationLifetimeObjects.Add(webcontext);
    11
    }
    Copied!
  4. 4.
    If you are using Windows Authentication or you want to load a user who has persisted credentials, call the LoadUser method before giving the user the option to log in.
    The following example shows how to call the LoadUser method from the Application_Startup method.
    1
    Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup
    2
    WebContext.Current.Authentication.LoadUser(AddressOf OnLoadUser_Completed, Nothing)
    3
    Me.RootVisual = New MainPage()
    4
    End Sub
    5
    ​
    6
    Private Sub OnLoadUser_Completed(ByVal operation As LoadUserOperation)
    7
    ' Update UI, if necessary
    8
    End Sub
    Copied!
    1
    private void Application_Startup(object sender, StartupEventArgs e)
    2
    {
    3
    WebContext.Current.Authentication.LoadUser(OnLoadUser_Completed, null);
    4
    this.RootVisual = new MainPage();
    5
    }
    6
    ​
    7
    private void OnLoadUser_Completed(LoadUserOperation operation)
    8
    {
    9
    // update UI, if necessary
    10
    }
    Copied!
  5. 5.
    If necessary, add a page to the client project for collecting user credentials.
  6. 6.
    In the code-behind file for the login page, call the Login method to login users.
    The following example shows how to call the Login method from an event handler for a login button. A callback method is included to respond to the results of the login operation.
    1
    Private Sub LoginButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    2
    Dim lp As LoginParameters = New LoginParameters(UserName.Text, Password.Password)
    3
    WebContext.Current.Authentication.Login(lp, AddressOf Me.LoginOperation_Completed, Nothing)
    4
    LoginButton.IsEnabled = False
    5
    LoginResult.Text = ""
    6
    End Sub
    7
    ​
    8
    Private Sub LoginOperation_Completed(ByVal lo As LoginOperation)
    9
    If (lo.HasError) Then
    10
    LoginResult.Text = lo.Error.Message
    11
    LoginResult.Visibility = System.Windows.Visibility.Visible
    12
    lo.MarkErrorAsHandled()
    13
    ElseIf (lo.LoginSuccess = False) Then
    14
    LoginResult.Text = "Login failed. Please check user name and password."
    15
    LoginResult.Visibility = System.Windows.Visibility.Visible
    16
    ElseIf (lo.LoginSuccess = True) Then
    17
    SetControlVisibility(True)
    18
    End If
    19
    LoginButton.IsEnabled = True
    20
    End Sub
    Copied!
    1
    private void LoginButton_Click(object sender, RoutedEventArgs e)
    2
    {
    3
    LoginParameters lp = new LoginParameters(UserName.Text, Password.Password);
    4
    WebContext.Current.Authentication.Login(lp, this.LoginOperation_Completed, null);
    5
    LoginButton.IsEnabled = false;
    6
    LoginResult.Text = "";
    7
    }
    8
    ​
    9
    private void LoginOperation_Completed(LoginOperation lo)
    10
    {
    11
    if (lo.HasError)
    12
    {
    13
    LoginResult.Text = lo.Error.Message;
    14
    LoginResult.Visibility = System.Windows.Visibility.Visible;
    15
    lo.MarkErrorAsHandled();
    16
    }
    17
    else if (lo.LoginSuccess == false)
    18
    {
    19
    LoginResult.Text = "Login failed. Please check user name and password.";
    20
    LoginResult.Visibility = System.Windows.Visibility.Visible;
    21
    }
    22
    else if (lo.LoginSuccess == true)
    23
    {
    24
    SetControlVisibility(true);
    25
    }
    26
    LoginButton.IsEnabled = true;
    27
    }
    Copied!
  7. 7.
    To logout users, call the Logout method.
    The following example shows how to call the Logout method from an event handler for a logout button. A callback method is included to respond to the results of the logout operation.
    1
    Private Sub LogoutButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    2
    WebContext.Current.Authentication.Logout(AddressOf Me.LogoutOperation_Completed, Nothing)
    3
    End Sub
    4
    ​
    5
    Private Sub LogoutOperation_Completed(ByVal lo As LogoutOperation)
    6
    If (Not (lo.HasError)) Then
    7
    SetControlVisibility(False)
    8
    Else
    9
    Dim ew As ErrorWindow = New ErrorWindow("Logout failed.", "Please try logging out again.")
    10
    ew.Show()
    11
    lo.MarkErrorAsHandled()
    12
    End If
    13
    End Sub
    Copied!
    1
    private void LogoutButton_Click(object sender, RoutedEventArgs e)
    2
    {
    3
    WebContext.Current.Authentication.Logout(this.LogoutOperation_Completed, null);
    4
    }
    5
    ​
    6
    private void LogoutOperation_Completed(LogoutOperation lo)
    7
    {
    8
    ​
    9
    if (!lo.HasError)
    10
    {
    11
    SetControlVisibility(false);
    12
    }
    13
    else
    14
    {
    15
    ErrorWindow ew = new ErrorWindow("Logout failed.", "Please try logging out again.");
    16
    ew.Show();
    17
    lo.MarkErrorAsHandled();
    18
    }
    19
    }
    Copied!
  8. 8.
    To check whether a user is authenticated, retrieve the IsAuthenticated property on the generated User entity.
    The following example checks if the current user is authenticated before retrieving a profile property and calling a domain operation.
    1
    Private Sub LoadReports()
    2
    If (WebContext.Current.User.IsAuthenticated) Then
    3
    numberOfRows = WebContext.Current.User.DefaultRows
    4
    AddHandler WebContext.Current.User.PropertyChanged, AddressOf User_PropertyChanged
    5
    LoadRestrictedReports()
    6
    Else
    7
    CustomersGrid.Visibility = System.Windows.Visibility.Collapsed
    8
    SalesOrdersGrid.Visibility = System.Windows.Visibility.Collapsed
    9
    End If
    10
    ​
    11
    Dim loadProducts = context.Load(context.GetProductsQuery().Take(numberOfRows))
    12
    ProductsGrid.ItemsSource = loadProducts.Entities
    13
    End Sub
    Copied!
    1
    private void LoadReports()
    2
    {
    3
    if (WebContext.Current.User.IsAuthenticated)
    4
    {
    5
    numberOfRows = WebContext.Current.User.DefaultRows;
    6
    WebContext.Current.User.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(User_PropertyChanged);
    7
    LoadRestrictedReports();
    8
    }
    9
    else
    10
    {
    11
    CustomersGrid.Visibility = System.Windows.Visibility.Collapsed;
    12
    SalesOrdersGrid.Visibility = System.Windows.Visibility.Collapsed;
    13
    }
    14
    ​
    15
    LoadOperation<Product> loadProducts = context.Load(context.GetProductsQuery().Take(numberOfRows));
    16
    ProductsGrid.ItemsSource = loadProducts.Entities;
    17
    }
    Copied!
  9. 9.
    If you want to make the WebContext object available in XAML, add the current WebContext instance to the application resources in the Application.Startup event before creating the root visual.
    The following example shows how to add the WebContext instance as an application resource.
    1
    Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup
    2
    Me.Resources.Add("WebContext", WebContext.Current)
    3
    Me.RootVisual = New MainPage()
    4
    End Sub
    Copied!
    1
    private void Application_Startup(object sender, StartupEventArgs e)
    2
    {
    3
    this.Resources.Add("WebContext", WebContext.Current);
    4
    this.RootVisual = new MainPage();
    5
    }
    Copied!

See Also

Tasks

Last modified 6mo ago