Export (0) Print
Expand All

How to: Enable Authentication in RIA Services

WCF RIA Services

[WCF RIA Services Version 1 Service Pack 2 is compatible with either .NET framework 4 or .NET Framework 4.5, and with either Silverlight 4 or Silverlight 5.]

This topic demonstrates how to enable user authentication in your application by using WCF 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 WCF 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. In the server project, open the Web.config file.

  2. In the <system.web> element, add an <authentication> element.

  3. Set the mode property to the authentication mode that you will use in the project.

    The following code shows the <authentication> 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.

    RIA_ServicesAddAuth
  7. Click Add.

  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.

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

    public App()
    {
        this.Startup += this.Application_Startup;
        this.UnhandledException += this.Application_UnhandledException;
    
        InitializeComponent();
    
        WebContext webcontext = new WebContext();
        webcontext.Authentication = new System.ServiceModel.DomainServices.Client.ApplicationServices.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 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. 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.

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

    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 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 void Application_Startup(object sender, StartupEventArgs e)
    {
        this.Resources.Add("WebContext", WebContext.Current);
        this.RootVisual = new MainPage();
    }
    
    
    
Show:
© 2014 Microsoft