Служба доменной аутентификации домена - Silverlight и RIA - PullRequest
0 голосов
/ 18 декабря 2011

Я пытаюсь написать пользовательскую службу проверки подлинности домена. Я думаю, что я понял весь код, который был написан на этом блоге .

Однако я не знаю, как указать, какое приложение службы домена следует использовать. У меня есть одна абстрактная служба домена, а вторая - конкретная реализация этой службы. Если я строю полное решение, я получаю ошибку

'MainModule.Web.FormsAuthenticationService`1' is not a valid DomainService type. DomainService types cannot be abstract or generic.

Я не нашел исходного кода в блоге, о котором упоминал ранее.

namespace MainModule.Web
{
    using System;
    using System.ServiceModel.DomainServices.Hosting;
    using System.ServiceModel.DomainServices.Server;



    // TODO: Create methods containing your application logic.
    [EnableClientAccess()]
    public abstract class FormsAuthenticationService<TUser> : DomainService, IAuthentication<TUser> where TUser : UserBase
    {

        protected abstract TUser GetCurrentUser(string name, string userData);
        protected abstract TUser ValidateCredentials(string name, string password, string customData, out string userData);
        protected virtual TUser GetDefaultUser()
        {
            return null;
        }

        public TUser GetUser()
        {
            IPrincipal currentUser = ServiceContext.User;
            if ((currentUser != null) && currentUser.Identity.IsAuthenticated)
            {
                FormsIdentity userIdentity = currentUser.Identity as FormsIdentity;
                if (userIdentity != null)
                {
                    FormsAuthenticationTicket ticket = userIdentity.Ticket;
                    if (ticket != null)
                    {
                        return GetCurrentUser(currentUser.Identity.Name, ticket.UserData);
                    }
                }
            }

            return GetDefaultUser();
        }

        public TUser Login(string userName, string password, bool isPersistent, string customData)
        {
            string userData;
            TUser user = ValidateCredentials(userName, password, customData, out userData);

            if (user != null)
            {
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(/* version */ 1, userName,
                                                           DateTime.Now, DateTime.Now.AddMinutes(30),
                                                           isPersistent,
                                                           userData,
                                                           FormsAuthentication.FormsCookiePath);

                string encryptedTicket = FormsAuthentication.Encrypt(ticket);
                HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

                HttpContextBase httpContext = (HttpContextBase)ServiceContext.GetService(typeof(HttpContextBase));
                httpContext.Response.Cookies.Add(authCookie);
            }
            else
            {
                HttpContextBase httpContext = (HttpContextBase)ServiceContext.GetService(typeof(HttpContextBase));
                httpContext.AddError(new FormsAuthenticationLogonException("Username or password is not correct."));
            }

            return user;
        }

        public TUser Logout()
        {
            FormsAuthentication.SignOut();
            return GetDefaultUser();
        }

        public void UpdateUser(TUser user)
        {
            throw new NotImplementedException();
        }
    }
}

namespace MainModule.Web
    {
        using System.ServiceModel.DomainServices.Hosting;
        // TODO: Create methods containing your application logic.
        [EnableClientAccess()]
        public class CustomAuthenticationService :FormsAuthenticationService<UserDTO>
        {
            protected override UserDTO GetCurrentUser(string name, string userData)
            {
                return new UserDTO {DisplayName = name, Name = name};
            }

            protected override UserDTO ValidateCredentials(string name, string password, string customData, out string userData)
            {
                userData = null;
                UserDTO user = null;


               if(name=="John" && password = "123")
               {
                    userData = name;
                    user =  new UserDTO {DisplayName = name, Email = "asdf"};

                 }
              retrurn user;
            }
        }
    }

Это классы, которые я реализовал - это тот же код, который размещен в блоге. Нет никаких исключений, поэтому я не могу вставить stackTrace. Я просто не могу скомпилировать решение

Ответы [ 2 ]

0 голосов
/ 24 сентября 2013

удалить атрибут [EnableClientAccess()] из абстрактного класса FormsAuthenticationService.скомпилируется без ошибок

0 голосов
/ 18 декабря 2011

Убедитесь, что вы используете правильные пространства имен.

Я заметил две небольшие опечатки в вставленном вами коде:

  1. if(name=="John" && password = "123")
    Должно быть:
    if (name=="John" && password == "123")

  2. retrurn user;
    Должно быть:
    return user;

В противном случае, оно компилируется без ошибок для меня.

  1. Создать новое веб-приложение

  2. Добавить ссылку на System.ServiceModel.DomainServices.Hosting (например, из "C: \ Program Files (x86) \ Microsoft SDKs \ RIA Services \ v1".0 \ Libraries \ Server \ System.ServiceModel.DomainServices.Hosting.dll ")

  3. Добавить ссылку на System.ServiceModel.DomainServices.Server (например, из" C: \ Program Files (x86) "\ Microsoft SDKs \ RIA Services \ v1.0 \ Libraries \ Server \ System.ServiceModel.DomainServices.Server.dll ")

  4. Создайте класс с именем CustomAuthenticationService и вставьте следующий код,

    using System.ServiceModel.DomainServices.Hosting;
    using System.Web;
    using System.Web.Security;
    using System;
    using System.Security.Principal;
    using System.ServiceModel.DomainServices.Server;
    using System.ServiceModel.DomainServices.Server.ApplicationServices;
    
    namespace WebApplication1.Services
    {
        public class UserDTO : UserBase
        {
            public string DisplayName { get; set; }
            public string Email { get; set; }
        }
    
        public class FormsAuthenticationLogonException : System.Exception
        {
            public FormsAuthenticationLogonException(string message) : base(message) { }
        }
    
        // TODO: Create methods containing your application logic.
        [EnableClientAccess()]
        public abstract class FormsAuthenticationService<TUser> : DomainService, IAuthentication<TUser> where TUser : UserBase
        {
    
            protected abstract TUser GetCurrentUser(string name, string userData);
            protected abstract TUser ValidateCredentials(string name, string password, string customData, out string userData);
            protected virtual TUser GetDefaultUser()
            {
                return null;
            }
    
            public TUser GetUser()
            {
                IPrincipal currentUser = ServiceContext.User;
                if ((currentUser != null) && currentUser.Identity.IsAuthenticated)
                {
                    FormsIdentity userIdentity = currentUser.Identity as FormsIdentity;
                    if (userIdentity != null)
                    {
                        FormsAuthenticationTicket ticket = userIdentity.Ticket;
                        if (ticket != null)
                        {
                            return GetCurrentUser(currentUser.Identity.Name, ticket.UserData);
                        }
                    }
                }
    
                return GetDefaultUser();
            }
    
            public TUser Login(string userName, string password, bool isPersistent, string customData)
            {
                string userData;
                TUser user = ValidateCredentials(userName, password, customData, out userData);
    
                if (user != null)
                {
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(/* version */ 1, userName,
                                                           DateTime.Now, DateTime.Now.AddMinutes(30),
                                                           isPersistent,
                                                           userData,
                                                           FormsAuthentication.FormsCookiePath);
    
                    string encryptedTicket = FormsAuthentication.Encrypt(ticket);
                    HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
    
                    HttpContextBase httpContext = (HttpContextBase)ServiceContext.GetService(typeof(HttpContextBase));
                    httpContext.Response.Cookies.Add(authCookie);
                }
                else
                {
                    HttpContextBase httpContext = (HttpContextBase)ServiceContext.GetService(typeof(HttpContextBase));
                    httpContext.AddError(new FormsAuthenticationLogonException("Username or password is not correct."));
                }
    
                return user;
            }
    
            public TUser Logout()
            {
                FormsAuthentication.SignOut();
                return GetDefaultUser();
            }
    
            public void UpdateUser(TUser user)
            {
                throw new NotImplementedException();
            }
        }
    
        // TODO: Create methods containing your application logic.
        [EnableClientAccess()]
        public class CustomAuthenticationService : FormsAuthenticationService<UserDTO>
        {
            protected override UserDTO GetCurrentUser(string name, string userData)
            {
                return new UserDTO { DisplayName = name, Name = name };
            }
    
            protected override UserDTO ValidateCredentials(string name, string password, string customData, out string userData)
            {
                userData = null;
                UserDTO user = null;
    
    
                if (name == "John" && password == "123")
                {
                    userData = name;
                    user = new UserDTO { DisplayName = name, Email = "asdf" };
    
                }
    
                return user;
            }
        }
    }
    
...