次の方法で共有


方法: RIA Services で認証を有効にする

ここでは、WCF RIA サービス を使用してアプリケーションでユーザー認証を有効にする方法について説明します。ここでは、クライアント アプリケーションで認証をサービスとして使用できるように、サーバー プロジェクトとクライアント プロジェクトの両方に追加する必要があるコードを示します。RequiresAuthenticationAttribute 属性をドメイン操作に適用して、そのドメイン操作へのアクセスを認証されているユーザーのみに制限できます。

WCF RIA サービス の認証は、ASP.NET の認証フレームワークに基づいて構築されています。ASP.NET 認証の詳細については、「メンバーシップの概要」を参照してください。

サーバー プロジェクトを構成するには

  1. サーバー プロジェクトで Web.config ファイルを開きます。

  2. <system.web> 要素に <authentication> 要素を追加します。

  3. mode プロパティを、プロジェクトで使用する認証モードに設定します。

    次のコードは、mode プロパティが Forms に設定された <authentication> 要素を示しています。Windows 認証を使用するには、mode プロパティを 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 プロパティを、サーバー プロジェクトで構成した認証の種類に設定し、ApplicationLifetimeObjectsWebContext インスタンスを追加します。

    次の例は、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. XAML で WebContext オブジェクトを使用できるようにする場合は、ルート visual を作成する前に、Application.Startup イベントのアプリケーション リソースに現在の WebContext インスタンスを追加します。

    次の例は、アプリケーション リソースとして 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 ビジネス アプリケーションでの認証サービスの使用