共用方式為


HOW TO:啟用 RIA Services 中的驗證

本主題將示範如何使用 WCF RIA Services 在您的應用程式中啟用使用者驗證,並顯示必須同時加入至伺服器專案與用戶端專案的程式碼,讓驗證以服務方式提供給用戶端應用程式使用。將 RequiresAuthenticationAttribute 屬性套用至網域作業,即可限制只有經過驗證的使用者才能存取網域作業。

WCF RIA Services 中的驗證是以 ASP.NET 中的驗證架構為建置基礎。如需 ASP.NET 驗證的詳細資訊,請參閱成員資格簡介

若要設定伺服器專案

  1. 在伺服器專案中,開啟 Web.config 檔案。

  2. <system.web> 項目中加入 <authentication> 項目。

  3. mode 屬性設為要用於專案的驗證模式。

    下列程式碼顯示 mode 設為 Forms<authentication> 項目。將 mode 屬性設為 Windows,以便使用 Windows 驗證。您的 Web.config 檔案將會包含其他項目。

    <system.web>
      <authentication mode="Forms"></authentication>
    </system.web>
    
  4. 儲存 Web.config 檔案。

  5. 在 [方案總管] 中,以滑鼠右鍵按一下伺服器專案,然後選取 [加入],再選取 [新增項目]。

    [加入新項目] 對話方塊隨即出現。

  6. 選取 [驗證 DomainService] 範本,並指定服務的名稱。

    RIA_ServicesAddAuth

  7. 按一下 [加入]。

  8. 若要限制只有經過驗證的使用者才能存取網域作業,請將 RequiresAuthenticationAttribute 屬性套用至網域作業。

    下列範例會指定只有經過驗證的使用者才能存取 GetSalesOrderHeaders 方法。

    <RequiresAuthentication()> _
    Public Function GetSalesOrderHeaders() As IQueryable(Of SalesOrderHeader)
        Return Me.ObjectContext.SalesOrderHeaders
    End Function
    
    [RequiresAuthentication()]
    public IQueryable<SalesOrderHeader> GetSalesOrderHeaders()
    {
        return this.ObjectContext.SalesOrderHeaders;
    }
    
  9. 建置方案。

若要在用戶端專案上設定驗證服務

  1. 在用戶端專案中,開啟 App.xaml 檔案的程式碼後置檔案 (App.xaml.cs 或 App.xaml.vb)。

  2. 在建構函式中,建立 WebContext 類別的執行個體。

  3. Authentication 屬性設為伺服器專案中設定的驗證類型,並將 WebContext 執行個體加入至 ApplicationLifetimeObjects

    下列範例示範如何將驗證設為 FormsAuthentication

    Public Sub New()
        InitializeComponent()
    
        Dim webcontext As New WebContext
        webcontext.Authentication = New System.ServiceModel.DomainServices.Client.ApplicationServices.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 System.ServiceModel.DomainServices.Client.ApplicationServices.FormsAuthentication();
        this.ApplicationLifetimeObjects.Add(webcontext);
    }
    
  4. 如果您使用 Windows 驗證或想要載入有永續性認證的使用者,請在為該使用者提供登入選項之前先呼叫 LoadUser 方法。

    下列範例示範如何從 Application_Startup 方法呼叫 LoadUser 方法。

    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. 如果必要的話,請在用戶端專案中加入一個用來收集使用者認證的頁面。

  6. 在登入頁面的程式碼後置檔案中,呼叫 Login 方法來登入使用者。

    下列範例示範如何從登入按鈕的事件處理常式呼叫 Login 方法。其中包含呼回方法,回應登入作業的結果。

    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. 若要登出使用者,請呼叫 Logout 方法。

    下列範例示範如何從登出按鈕的事件處理常式呼叫 Logout 方法。其中包含呼回方法,回應登出作業的結果。

    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. 若要檢查使用者是否經過驗證,請擷取產生的 User 實體上的 IsAuthenticated 屬性。

    下列範例會在擷取設定檔屬性並呼叫網域作業之前檢查目前的使用者是否經過驗證。

    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. 如果您想要讓 WebContext 物件可以在 XAML 中使用,請將目前的 WebContext 執行個體加入至 Application.Startup 事件中的應用程式資源,然後再建立根 Visual。

    下列範例示範如何加入 WebContext 執行個體做為應用程式資源。

    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();
    }
    

另請參閱

工作

逐步解說:搭配 Silverlight 瀏覽應用程式使用驗證服務
逐步解說:搭配 Silverlight 商務應用程式使用驗證服務