Exemplo n.º 1
0
 private static void OnRequests(SocketChannel channel, HttpRequestBase request)
 {
     var response = request.CreateResponse();
     response.StatusCode = 200;
     response.Body = GetStream();
     response.AddHeader("Keep-Alive", "timeout=15, max=100");
     response.Body.Write(Encoding.ASCII.GetBytes("HelloWorld"), 0, 10);
     channel.Send(response);
 }
        private bool AuthenticateUser(ITcpChannel channel, HttpRequestBase request)
        {
            if (channel.Data["Principal"] != null)
            {
                Thread.CurrentPrincipal = (IPrincipal) channel.Data["Principal"];
                return true;
            }

            try
            {
                var user = Authenticator.Authenticate(request);
                if (user == null)
                    return true;

                if (PrincipalFactory != null)
                {
                    var ctx = new PrincipalFactoryContext(request, user);
                    Thread.CurrentPrincipal = PrincipalFactory.Create(ctx);
                    channel.Data["Principal"] = Thread.CurrentPrincipal;
                    return true;
                }

                var roles = user as IUserWithRoles;
                if (roles == null)
                    throw new InvalidOperationException(
                        "You must specify a PrincipalFactory if you do not return a IUserWithRoles from your IAccountService.");

                Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(user.Username), roles.RoleNames);
                channel.Data["Principal"] = Thread.CurrentPrincipal;
            }
            catch (HttpException ex)
            {
                if (Logger != null)
                    Logger("Authentication failed.\r\nException:\r\n" + ex.ToString());
                var response = request.CreateResponse();
                response.StatusCode = ex.HttpCode;
                response.ReasonPhrase = FirstLine(ex.Message);
                channel.Send(response);
                return false;
            }

            return true;
        }