방법: RIA Services에서 인증 사용

이 항목에서는 WCF RIA Services를 사용하여 응용 프로그램에 사용자 인증을 설정하는 방법에 대해 설명하고, 클라이언트 응용 프로그램에서 인증을 서비스로 사용할 수 있도록 서버 프로젝트와 클라이언트 프로젝트 모두에 추가해야 하는 코드를 보여 줍니다. 도메인 작업에 RequiresAuthenticationAttribute 특성을 적용하여 도메인 작업에 대한 액세스를 인증된 사용자로만 제한할 수 있습니다.

WCF RIA Services의 인증은 ASP.NET의 인증 프레임워크를 기반으로 합니다. ASP.NET 인증에 대한 자세한 내용은 Introduction to Membership을 참조하십시오.

서버 프로젝트를 구성하려면

  1. 서버 프로젝트에서 Web.config 파일을 엽니다.

  2. <system.web> 요소에서 <authentication> 요소를 추가합니다.

  3. mode 속성을 프로젝트에서 사용할 인증 모드로 설정합니다.

    다음 코드에서는 modeForms으로 설정된 <authentication> 요소를 보여 줍니다. Windows 인증을 사용하려면 mode 속성을 Windows로 설정합니다. 이렇게 하면 Web.config 파일에 다른 요소가 포함됩니다.

    <system.web>
      <authentication mode="Forms"></authentication>
    </system.web>
    
  4. Web.config 파일을 저장합니다.

  5. 솔루션 탐색기에서 서버 프로젝트를 마우스 오른쪽 단추로 클릭하고 추가를 선택한 다음 새 항목을 선택합니다.

    새 항목 추가 대화 상자가 나타납니다.

  6. 인증 도메인 서비스 템플릿을 선택하고 서비스의 이름을 지정합니다.

    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 비즈니스 응용 프로그램에서 인증 서비스 사용