📒
OpenRiaServices
  • Start
  • Prerequisites for Open Ria Services
    • Walkthrough: Installing and Configuring SQL Server 2008 R2 Express with Advanced Services
    • Walkthrough: Installing the AdventureWorks OLTP and LT sample databases
  • Creating Open Ria Services Solutions
    • Walkthrough: Taking a Tour of Open Ria Services
    • Walkthrough: Creating a Open Ria Services Solution
    • Walkthrough: Creating a Open Ria Service with the Code First Approach
    • Walkthrough: Using the Silverlight Business Application Template
    • Walkthrough: Creating a Open Ria Services Class Library
    • Walkthrough: Localizing a Business Application
    • How to: Create a Domain Service that uses POCO-defined Entities
    • How to: Add or Remove a Open Ria Services Link
    • Using the Domain Service Wizard
  • Building Secure Applications with Open Ria Services
  • Deploying and Localizing a Open Ria Services Solutions
    • Troubleshooting the Deployment of a Open Ria Services Solution
    • Troubleshooting the Deployment of a Open Ria Services Solution
    • Walkthrough: Localizing a Business Application
  • Middle Tier
    • Domain Services
      • Walkthrough: Adding Query Methods
      • How to: Add Business Logic to the Domain Service
      • How to: Create a Domain Service that uses POCO-defined Entities
      • How to: Use HTTPS with a Domain Service
    • Data
      • Compositional Hierarchies
      • Presentation Models
      • Inheritance in Data Models
      • Complex Types
      • Shared Entities
      • Walkthrough: Sharing Entities between Multiple Domain Services
      • How to: Add Metadata Classes
      • How to: Validate Data
      • Managing Data Concurrency
    • Shared Code
      • How to: Share Code through Source Files
      • Walkthrough: Creating a Open Ria Services Class Library
  • Silverlight Clients
    • Client Code Generation
    • DomainContext and Operations
    • DomainDataSource
    • Error Handling on the Client
    • Customizing Generated Code
      • How to: Add Computed Properties on the Client
  • Accessing non-Silverlight Clients
    • ASP.NET Clients
    • Walkthrough: Using the Domain Service in ASP.NET Applications
  • Authentication, Roles, and Profiles
    • How to: Enable Authentication in Open Ria Services
    • How to: Enable Roles in Open Ria Services
    • How to: Enable Profiles in Open Ria Services
    • How to: Create a Custom Authorization Attribute
    • Walkthrough: Using Authentication Service with Silverlight Business Application
    • Walkthrough: Using Authentication Service with Silverlight Navigation Application
  • End-to-EndScenarios
    • Walkthrough: Retrieving and Displaying Data From a Domain Service
    • Walkthrough: Editing Data From a Domain Service
    • Walkthrough: Displaying Data in a Silverlight Business Application
    • Walkthrough: Displaying Related Data in a Silverlight Business Application
Powered by GitBook
On this page
  • To configure the server project
  • To configure the authentication service on the client project
  • See Also

Was this helpful?

  1. Authentication, Roles, and Profiles

How to: Enable Authentication in Open Ria Services

PreviousAuthentication, Roles, and ProfilesNextHow to: Enable Roles in Open Ria Services

Last updated 4 years ago

Was this helpful?

[ This document was written for WCF Services Version 1 Service Pack 2 and might not be up to date Please see or 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 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 .

To configure the server project

  1. In the server project, open the Web.config file.

  2. In the \ element, add an \ element.

  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.

    <system.web>
      <authentication mode="Forms"></authentication>
    </system.web>
  4. Save the Web.config file.

  5. In Solution Explorer, right-click the server project, select Add and then New Item.

    The Add New Item dialog box appears.

  6. Select the Authentication Domain Service template and specify a name for the service.

  7. Click Add.

  8. To restrict access to a domain operation to only authenticated users, apply the attribute to the domain operation.

    The following example specifies that only authenticated users can access the GetSalesOrderHeaders method.

    <RequiresAuthentication()> _
    Public Function GetSalesOrderHeaders() As IQueryable(Of SalesOrderHeader)
        Return Me.ObjectContext.SalesOrderHeaders
    End Function
    [RequiresAuthentication()]
    public IQueryable<SalesOrderHeader> GetSalesOrderHeaders()
    {
        return this.ObjectContext.SalesOrderHeaders;
    }
  9. Build the solution.

To configure the authentication service on the client project

  1. In the client project, open the code-behind file for the App.xaml file (App.xaml.cs or App.xaml.vb).

  2. In the constructor, create an instance of the WebContext class.

  3. Public Sub New()
        InitializeComponent()
    
        Dim webcontext As New WebContext
        webcontext.Authentication = New OpenRiaServices.Client.Authentication.FormsAuthentication
        Me.ApplicationLifetimeObjects.Add(webcontext)
    End Sub
    public App()
    {
        this.Startup += this.Application_Startup;
        this.UnhandledException += this.Application_UnhandledException;
    
        InitializeComponent();
    
        WebContext webcontext = new WebContext();
        webcontext.Authentication = new OpenRiaServices.Client.Authentication.FormsAuthentication();
        this.ApplicationLifetimeObjects.Add(webcontext);
    }
  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.

    Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup
        WebContext.Current.Authentication.LoadUser(AddressOf OnLoadUser_Completed, Nothing)
        Me.RootVisual = New MainPage()
    End Sub
    
    Private Sub OnLoadUser_Completed(ByVal operation As LoadUserOperation)
        ' Update UI, if necessary
    End Sub
    private void Application_Startup(object sender, StartupEventArgs e)
    {
        WebContext.Current.Authentication.LoadUser(OnLoadUser_Completed, null);
        this.RootVisual = new MainPage();
    }
    
    private void OnLoadUser_Completed(LoadUserOperation operation)
    {
        // update UI, if necessary
    }
  5. If necessary, add a page to the client project for collecting user credentials.

  6. 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.

    Private Sub LoginButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim lp As LoginParameters = New LoginParameters(UserName.Text, Password.Password)
        WebContext.Current.Authentication.Login(lp, AddressOf Me.LoginOperation_Completed, Nothing)
        LoginButton.IsEnabled = False
        LoginResult.Text = ""
    End Sub
    
    Private Sub LoginOperation_Completed(ByVal lo As LoginOperation)
        If (lo.HasError) Then
            LoginResult.Text = lo.Error.Message
            LoginResult.Visibility = System.Windows.Visibility.Visible
            lo.MarkErrorAsHandled()
        ElseIf (lo.LoginSuccess = False) Then
            LoginResult.Text = "Login failed. Please check user name and password."
            LoginResult.Visibility = System.Windows.Visibility.Visible
        ElseIf (lo.LoginSuccess = True) Then
            SetControlVisibility(True)
        End If
        LoginButton.IsEnabled = True
    End Sub
    private void LoginButton_Click(object sender, RoutedEventArgs e)
    {
        LoginParameters lp = new LoginParameters(UserName.Text, Password.Password);
        WebContext.Current.Authentication.Login(lp, this.LoginOperation_Completed, null);
        LoginButton.IsEnabled = false;
        LoginResult.Text = "";
    }
    
    private void LoginOperation_Completed(LoginOperation lo)
    {
        if (lo.HasError)
        {
            LoginResult.Text = lo.Error.Message;
            LoginResult.Visibility = System.Windows.Visibility.Visible;
            lo.MarkErrorAsHandled();
        }
        else if (lo.LoginSuccess == false)
        {
            LoginResult.Text = "Login failed. Please check user name and password.";
            LoginResult.Visibility = System.Windows.Visibility.Visible;
        }
        else if (lo.LoginSuccess == true)
        {
            SetControlVisibility(true);
        }
        LoginButton.IsEnabled = true;
    }
  7. 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.

    Private Sub LogoutButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        WebContext.Current.Authentication.Logout(AddressOf Me.LogoutOperation_Completed, Nothing)
    End Sub
    
    Private Sub LogoutOperation_Completed(ByVal lo As LogoutOperation)
        If (Not (lo.HasError)) Then
            SetControlVisibility(False)
        Else
            Dim ew As ErrorWindow = New ErrorWindow("Logout failed.", "Please try logging out again.")
            ew.Show()
            lo.MarkErrorAsHandled()
        End If
    End Sub
    private void LogoutButton_Click(object sender, RoutedEventArgs e)
    {
        WebContext.Current.Authentication.Logout(this.LogoutOperation_Completed, null);
    }
    
    private void LogoutOperation_Completed(LogoutOperation lo)
    {
    
        if (!lo.HasError)
        {
            SetControlVisibility(false);
        }
        else
        {
            ErrorWindow ew = new ErrorWindow("Logout failed.", "Please try logging out again.");
            ew.Show();
            lo.MarkErrorAsHandled();
        }
    }
  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.

    Private Sub LoadReports()
        If (WebContext.Current.User.IsAuthenticated) Then
            numberOfRows = WebContext.Current.User.DefaultRows
            AddHandler WebContext.Current.User.PropertyChanged, AddressOf User_PropertyChanged
            LoadRestrictedReports()
        Else
            CustomersGrid.Visibility = System.Windows.Visibility.Collapsed
            SalesOrdersGrid.Visibility = System.Windows.Visibility.Collapsed
        End If
    
        Dim loadProducts = context.Load(context.GetProductsQuery().Take(numberOfRows))
        ProductsGrid.ItemsSource = loadProducts.Entities
    End Sub
    private void LoadReports()
    {
        if (WebContext.Current.User.IsAuthenticated)
        {
            numberOfRows = WebContext.Current.User.DefaultRows;
            WebContext.Current.User.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(User_PropertyChanged);
            LoadRestrictedReports();
        }
        else
        {
            CustomersGrid.Visibility = System.Windows.Visibility.Collapsed;
            SalesOrdersGrid.Visibility = System.Windows.Visibility.Collapsed;
        }
    
        LoadOperation<Product> loadProducts = context.Load(context.GetProductsQuery().Take(numberOfRows));
        ProductsGrid.ItemsSource = loadProducts.Entities;
    }
  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.

    Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup
        Me.Resources.Add("WebContext", WebContext.Current)
        Me.RootVisual = New MainPage()
    End Sub
    private void Application_Startup(object sender, StartupEventArgs e)
    {
        this.Resources.Add("WebContext", WebContext.Current);
        this.RootVisual = new MainPage();
    }

See Also

Tasks

Set the 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 .

In the code-behind file for the login page, call the method to login users.

To logout users, call the method.

Authentication
FormsAuthentication
Login
Logout
Walkthrough: Using Authentication Service with Silverlight Navigation Application
Walkthrough: Using Authentication Service with Silverlight Business Application
Release Notes
Changelog
RequiresAuthenticationAttribute
Introduction to Membership
RequiresAuthenticationAttribute
RIA_ServicesAddAuth