Поделиться через


Интерфейс IReportServerCredentials

Разрешает приложениям предоставлять учетные данные для соединения с сервером отчетов служб Reporting Services.

Пространство имен:  Microsoft.Reporting.WebForms
Сборка:  Microsoft.ReportViewer.WebForms (в Microsoft.ReportViewer.WebForms.dll)

Синтаксис

'Декларация
Public Interface IReportServerCredentials
'Применение
Dim instance As IReportServerCredentials
public interface IReportServerCredentials
public interface class IReportServerCredentials
type IReportServerCredentials =  interface end
public interface IReportServerCredentials

Тип IReportServerCredentials обеспечивает доступ к следующим элементам.

Свойства

  Имя Описание
Открытое свойство ImpersonationUser Возвращает или задает олицетворение System.Security.Principal.WindowsIdentity пользователя, когда элемент управления ReportViewer соединяется с сервером отчетов.
Открытое свойство NetworkCredentials Возвращает или задает учетные данные сети, которые используются для проверки подлинности на сервере отчетов.

В начало

Методы

  Имя Описание
Открытый метод GetFormsCredentials Предоставляет сведения, которые используются для соединения с сервером отчетов, настроенным на проверку подлинности с помощью форм.

В начало

Замечания

При реализации интерфейса IReportServerCredentials важно знать, что элемент управления ReportViewer хранит экземпляр объекта в сеансе ASP.NET. Если сеанс ASP.NET сервера хранится вне процесса, например в службах Reporting Services, то класс необходимо пометить признаком Serializable, чтобы его можно было сериализовать для хранения.

Хотя это и не является обязательным, рекомендуется реализовать интерфейс IReportServerCredentials как объект без сохранения состояния. Это предотвращает сохранение учетных данных, таких как имя пользователя и пароль при сериализации объекта.

Дополнительные сведения о задании учетных данных с помощью элемента управления ReportViewer см. в разделе Задание соединений и учетных данных для серверного веб-элемента управления ReportViewer.

Примеры

Следующий пример содержит реализацию интерфейса IReportServerCredentials, помеченного признаком Serializable, чтобы его можно было сериализовать для хранения. Сведения об учетных данных получаются из файла Web.config. Эта реализация соединяется с сервером отчетов с одинаковыми учетными данными для всех клиентских запросов.

Прежде чем использовать этот пример, необходимо добавить три пары «ключ-значение» в файл Web.config приложения в блоке appSettings: MyReportViewerUser, MyReportViewerPassword и MyReportViewerDomain. Эти значения соответствуют имени пользователя, паролю и домену, которые используются при соединении с сервером отчетов.

using System;
using System.Data;
using System.Configuration;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.Reporting.WebForms;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Init(object sender, EventArgs e)
    {
        ReportViewer1.ServerReport.ReportServerCredentials = 
            new MyReportServerCredentials();
    }
}

[Serializable]
public sealed class MyReportServerCredentials : 
    IReportServerCredentials
{
    public WindowsIdentity ImpersonationUser
    {
        get
        {
            // Use the default Windows user.  Credentials will be
            // provided by the NetworkCredentials property.
            return null;
        }
    }

    public ICredentials NetworkCredentials
    {
        get
        {
            // Read the user information from the Web.config file.  
            // By reading the information on demand instead of 
            // storing it, the credentials will not be stored in 
            // session, reducing the vulnerable surface area to the
            // Web.config file, which can be secured with an ACL.

            // User name
            string userName = 
                ConfigurationManager.AppSettings
                    ["MyReportViewerUser"];

            if (string.IsNullOrEmpty(userName))
                throw new Exception(
                    "Missing user name from web.config file");

            // Password
            string password = 
                ConfigurationManager.AppSettings
                    ["MyReportViewerPassword"];

            if (string.IsNullOrEmpty(password))
                throw new Exception(
                    "Missing password from web.config file");

            // Domain
            string domain = 
                ConfigurationManager.AppSettings
                    ["MyReportViewerDomain"];

            if (string.IsNullOrEmpty(domain))
                throw new Exception(
                    "Missing domain from web.config file");

            return new NetworkCredential(userName, password, domain);
        }
    }

    public bool GetFormsCredentials(out Cookie authCookie, 
                out string userName, out string password, 
                out string authority)
    {
        authCookie = null;
        userName = null;
        password = null;
        authority = null;

        // Not using form credentials
        return false;
    }
}
Imports System.Net
Imports System.Security.Principal
Imports Microsoft.Reporting.WebForms

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Init(ByVal sender As Object, _
                            ByVal e As System.EventArgs) _
                            Handles Me.Init

        ReportViewer1.ServerReport.ReportServerCredentials = _
            New MyReportServerCredentials()

    End Sub

End Class

<Serializable()> _
Public NotInheritable Class MyReportServerCredentials
    Implements IReportServerCredentials

    Public ReadOnly Property ImpersonationUser() As WindowsIdentity _
            Implements IReportServerCredentials.ImpersonationUser
        Get

            'Use the default windows user.  Credentials will be
            'provided by the NetworkCredentials property.
            Return Nothing

        End Get
    End Property

    Public ReadOnly Property NetworkCredentials() As ICredentials _
            Implements IReportServerCredentials.NetworkCredentials
        Get

            'Read the user information from the web.config file.  
            'By reading the information on demand instead of storing 
            'it, the credentials will not be stored in session, 
            'reducing the vulnerable surface area to the web.config 
            'file, which can be secured with an ACL.

            'User name
            Dim userName As String = _
                ConfigurationManager.AppSettings("MyReportViewerUser")

            If (String.IsNullOrEmpty(userName)) Then
                Throw New Exception("Missing user name from web.config file")
            End If

            'Password
            Dim password As String = _
                ConfigurationManager.AppSettings("MyReportViewerPassword")

            If (String.IsNullOrEmpty(password)) Then
                Throw New Exception("Missing password from web.config file")
            End If

            'Domain
            Dim domain As String = _
                ConfigurationManager.AppSettings("MyReportViewerDomain")

            If (String.IsNullOrEmpty(domain)) Then
                Throw New Exception("Missing domain from web.config file")
            End If

            Return New NetworkCredential(userName, password, domain)

        End Get
    End Property

    Public Function GetFormsCredentials(ByRef authCookie As Cookie, _
                                        ByRef userName As String, _
                                        ByRef password As String, _
                                        ByRef authority As String) _
                                        As Boolean _
            Implements IReportServerCredentials.GetFormsCredentials

        authCookie = Nothing
        userName = Nothing
        password = Nothing
        authority = Nothing

        'Not using form credentials
        Return False

    End Function

End Class

См. также

Справочник

Пространство имен Microsoft.Reporting.WebForms

IReportServerConnection2