Exemplo n.º 1
0
        // Applies authentication for requests where credentials are passed directly in the HTTP headers.
        private SecurityPrincipal AuthenticateCachedCredentials(string authenticationToken)
        {
            string username, password;

            if ((object)authenticationToken == null)
            {
                return(null);
            }

            // Get the user's credentials from the credential cache
            if (!SessionHandler.TryGetCachedCredentials(authenticationToken, out username, out password))
            {
                return(null);
            }

            // Create the security provider that will authenticate the user's credentials
            ISecurityProvider securityProvider = SecurityProviderCache.CreateProvider(username, autoRefresh: false);

            securityProvider.Password = password;
            securityProvider.Authenticate();

            // Return the security principal that will be used for role-based authorization
            SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);

            return(new SecurityPrincipal(securityIdentity));
        }
        public ActionConfirmation ValidateUser(UserDto userToValidate)
        {
            Person user;

            try
            {
                _securityProvider.Authenticate(userToValidate.UserName, userToValidate.Password);
                if (!_securityProvider.IsAuthenticated)
                {
                    return(ActionConfirmation.CreateFailureConfirmation("Invalid network user name or password"));
                }
                user = _personRepository.GetByUserName(userToValidate.UserName);
                if (user == null)
                {
                    return(ActionConfirmation.CreateFailureConfirmation("User not found"));
                }
                return(ActionConfirmation.CreateSuccessConfirmation(""));
            }
            catch (InvalidPasswordException)
            {
                return(ActionConfirmation.CreateFailureConfirmation("Invalid network user name or password"));
            }
            catch (NetworkUserNotFoundException)
            {
                return(ActionConfirmation.CreateFailureConfirmation("Invalid Network User Name or Password"));
            }
            catch (Exception ex)
            {
                throw new Exception("Encountered an error while attempting to validate username and password", ex);
            }
        }
Exemplo n.º 3
0
            /// <summary>
            /// Refreshes the provider managed by this <see cref="CacheContext"/>.
            /// </summary>
            public bool Refresh()
            {
                try
                {
                    ISecurityProvider provider = _Provider;

                    if ((object)provider == null)
                    {
                        return(false);
                    }

                    if (provider.CanRefreshData)
                    {
                        provider.RefreshData();
                    }

                    provider.Authenticate();
                    LastRefreshTime = DateTime.UtcNow;

                    return(true);
                }
                catch (ObjectDisposedException)
                {
                    m_disposed = true;
                    return(false);
                }
            }
Exemplo n.º 4
0
        /// <summary>
        /// Changes user password.
        /// </summary>
        /// <param name="sender">Source of this event.</param>
        /// <param name="e">Arguments of this event.</param>
        protected void ChangeButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Initialize the security provider.
                ISecurityProvider provider = SecurityProviderUtility.CreateProvider(ChangePasswordUsername.Text);

                if (provider.CanChangePassword)
                {
                    // Attempt to change password.
                    if (provider.ChangePassword(ChangePasswordOldPassword.Text, ChangePasswordNewPassword.Text))
                    {
                        // Password changed successfully.
                        if (provider.Authenticate(ChangePasswordNewPassword.Text))
                        {
                            // Password authenticated successfully.
                            SecurityProviderCache.CurrentProvider = provider;
                            Response.Redirect(GetReferrerUrl(), false);
                        }
                        else
                        {
                            // Show why authentication failed.
                            if (!ShowFailureReason(provider))
                            {
                                ShowMessage("Authentication was not successful.", true);
                            }
                        }
                    }
                    else
                    {
                        // Show why password change failed.
                        if (!ShowFailureReason(provider))
                        {
                            ShowMessage("Password change was not successful.", true);
                        }
                    }
                }
                else
                {
                    // Changing password is not supported.
                    ShowMessage("Account does not support password change.", true);
                }
            }
            catch (SecurityException ex)
            {
                // Show security related error messages.
                ShowMessage(ex.Message.EnsureEnd('.'), true);
            }
            catch (Exception ex)
            {
                // Show ambiguous message for other errors.
                ShowMessage("Password change failed due to an unexpected error.", true);
                System.Diagnostics.Trace.WriteLine(string.Format("Password change error: \r\n  {0}", ex));
            }
            finally
            {
                ChangePasswordOldPassword.Focus();
            }
        }
Exemplo n.º 5
0
        private void SecureForm_Load(object sender, EventArgs e)
        {
            try
            {
                // Don't proceed if the form is opened in design mode
                if (DesignMode)
                {
                    return;
                }

                // Check if the resource is excluded from being secured
                string resource = GetResourceName();

                if (!SecurityProviderUtility.IsResourceSecurable(resource))
                {
                    return;
                }

                // Set up security provider for passthrough authentication
                ISecurityProvider securityProvider = SecurityProviderCache.CreateProvider(WindowsIdentity.GetCurrent().Name);
                securityProvider.PassthroughPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                securityProvider.Authenticate();

                // Setup the security principal for role-based security
                SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);
                SecurityPrincipal = new SecurityPrincipal(securityIdentity);

                // Verify that the current thread principal has been authenticated
                if (!SecurityPrincipal.Identity.IsAuthenticated)
                {
                    throw new SecurityException($"Authentication failed for user '{SecurityPrincipal.Identity.Name}'");
                }

                // Perform a top-level permission check on the resource being accessed
                if (!SecurityProviderUtility.IsResourceAccessible(resource, SecurityPrincipal))
                {
                    throw new SecurityException($"Access to '{resource}' is denied");
                }

                // Set up the current thread principal
                // NOTE: Provided for backwards compatibility;
                //       recommended to use the SecurityPrincipal instead
                Thread.CurrentPrincipal = SecurityPrincipal;
            }
            catch (Exception ex)
            {
                if (ExceptionHandler is null)
                {
                    throw;
                }

                ExceptionHandler(ex);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Authenticates a user and caches the security context upon successful authentication for subsequent use.
        /// </summary>
        /// <param name="username">Username of the user.</param>
        /// <param name="password">Password of the user.</param>
        /// <returns>An <see cref="UserData"/> object of the user.</returns>
        public UserData Authenticate(string username, string password)
        {
            ISecurityProvider provider = SecurityProviderUtility.CreateProvider(username);

            if (provider.Authenticate(password))
            {
                SecurityProviderCache.CurrentProvider = provider;
            }

            return(provider.UserData);
        }
Exemplo n.º 7
0
        private void ValidateCurrentProvider()
        {
            if (CurrentProvider == null)
            {
                ISecurityProvider securityProvider = SecurityProviderCache.CreateProvider(Thread.CurrentPrincipal.Identity.Name);
                securityProvider.PassthroughPrincipal = Thread.CurrentPrincipal;
                securityProvider.Authenticate();

                SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);
                Thread.CurrentPrincipal = new SecurityPrincipal(securityIdentity);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Authenticates a user and caches the security context upon successful authentication for subsequent use.
        /// </summary>
        /// <param name="username">Username of the user.</param>
        /// <param name="password">Password of the user.</param>
        /// <returns>An <see cref="UserData"/> object of the user.</returns>
        public UserData Authenticate(string username, string password)
        {
            ISecurityProvider securityProvider = SecurityProviderUtility.CreateProvider(username);

            securityProvider.Password = password;

            if (securityProvider.Authenticate())
            {
                SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);
                Thread.CurrentPrincipal = new SecurityPrincipal(securityIdentity);
            }

            return(securityProvider.UserData);
        }
Exemplo n.º 9
0
            /// <summary>
            /// Refreshes the provider managed by this <see cref="CacheContext"/>.
            /// </summary>
            public bool Refresh()
            {
                ISecurityProvider provider = Provider;

                if ((object)provider == null)
                {
                    return(false);
                }

                provider.RefreshData();
                provider.Authenticate();
                m_lastRefreshTime = DateTime.UtcNow;

                return(true);
            }
Exemplo n.º 10
0
        /// <summary>
        /// The authenticate.
        /// </summary>
        /// <param name="credentials">
        /// The user credentials.
        /// </param>
        /// <param name="flags">the flags</param>
        /// <returns>
        /// The auth payload
        /// </returns>
        internal static AuthPayload Authenticate(SecurityCredentials credentials, HashSet <string> flags = null)
        {
            AuthPayload result = null;

            if (authorizers.ContainsKey(credentials.SecurityProviderName) == true)
            {
                ISecurityProvider securityProvider = authorizers[credentials.SecurityProviderName];
                result = securityProvider.Authenticate(credentials, flags);
            }
            else
            {
                Log.Warn("Unregistered security provider was specified: {0}", credentials.SecurityProviderName);
            }

            return(result);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Attempts to reauthenticate the current thread principal
        /// after their provider has been removed from the cache.
        /// </summary>
        /// <returns>True if the user successfully reauthenticated; false otherwise.</returns>
        public static bool ReauthenticateCurrentPrincipal()
        {
            IPrincipal        currentPrincipal;
            SecurityIdentity  identity;
            ISecurityProvider provider = null;
            string            password = null;
            bool authenticated;

            currentPrincipal = Thread.CurrentPrincipal;

            if ((object)currentPrincipal == null)
            {
                return(false);
            }

            identity = currentPrincipal.Identity as SecurityIdentity;

            if ((object)identity != null)
            {
                provider = identity.Provider;
            }

            if ((object)provider != null)
            {
                password = provider.Password;
            }

            // Reset the current principal
            WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();

            if ((object)currentIdentity != null)
            {
                Thread.CurrentPrincipal = new WindowsPrincipal(currentIdentity);
            }

            // Create a new provider associated with current identity
            provider = SecurityProviderUtility.CreateProvider(currentPrincipal.Identity.Name);

            // Re-authenticate user
            authenticated = provider.Authenticate(password);

            // Re-cache current provider for user
            CurrentProvider = provider;

            return(authenticated);
        }
Exemplo n.º 12
0
        public async Task <ActionResult> Authenticate(AuthenticateModel authModel)
        {
            var authInfo = await _securityProvider.Authenticate(authModel.Email, authModel.Password);

            if (!authInfo.Result.Succeeded)
            {
                return(BadRequest(new IdentityError
                {
                    Code = "InvalidCredentials",
                    Description = "Invalid email or password."
                }));
            }

            return(Ok(new AuthResultModel
            {
                User = _mapper.Map <UserModel>(authInfo.User),
                Token = authInfo.Token
            }));
        }
Exemplo n.º 13
0
        // Applies authentication for requests where credentials are passed directly in the HTTP headers.
        private SecurityPrincipal AuthenticateBasic(string credentials)
        {
            string username, password;

            // Get the user's credentials from the HTTP headers
            if (!TryParseCredentials(credentials, out username, out password))
            {
                return(null);
            }

            // Create the security provider that will authenticate the user's credentials
            ISecurityProvider securityProvider = SecurityProviderCache.CreateProvider(username, autoRefresh: false);

            securityProvider.Password = password;
            securityProvider.Authenticate();

            // Return the security principal that will be used for role-based authorization
            SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);

            return(new SecurityPrincipal(securityIdentity));
        }
Exemplo n.º 14
0
        private ActionResult ValidateAdminRequest()
        {
            string            username         = HttpContext.User.Identity.Name;
            ISecurityProvider securityProvider = SecurityProviderUtility.CreateProvider(username);

            securityProvider.PassthroughPrincipal = HttpContext.User;

            if (!securityProvider.Authenticate())
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Forbidden));
            }

            SecurityIdentity  approverIdentity  = new SecurityIdentity(securityProvider);
            SecurityPrincipal approverPrincipal = new SecurityPrincipal(approverIdentity);

            if (!approverPrincipal.IsInRole("Administrator"))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Forbidden));
            }

            return(null);
        }
Exemplo n.º 15
0
        // Applies authentication for requests using Windows pass-through authentication.
        public static SecurityPrincipal AuthenticatePassthrough(IPrincipal user)
        {
            string username = user?.Identity.Name;

            if ((object)username == null)
            {
                return(null);
            }

            // Get the principal used for verifying the user's pass-through authentication
            IPrincipal passthroughPrincipal = user;

            // Create the security provider that will verify the user's pass-through authentication
            ISecurityProvider securityProvider = SecurityProviderCache.CreateProvider(username, passthroughPrincipal, false);

            securityProvider.Authenticate();

            // Return the security principal that will be used for role-based authorization
            SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);

            return(new SecurityPrincipal(securityIdentity));
        }
Exemplo n.º 16
0
        private void Application_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            // Check if access to resource is to be secured.
            string resource = GetResourceName();

            if (!IsAccessSecured(resource))
            {
                return;
            }

            SecurityPrincipal securityPrincipal = Thread.CurrentPrincipal as SecurityPrincipal;

            if ((object)securityPrincipal == null)
            {
                ISecurityProvider securityProvider = SecurityProviderCache.CreateProvider(Thread.CurrentPrincipal.Identity.Name);
                securityProvider.PassthroughPrincipal = Thread.CurrentPrincipal;
                securityProvider.Authenticate();

                SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);
                securityPrincipal = new SecurityPrincipal(securityIdentity);

                Thread.CurrentPrincipal = securityPrincipal;
            }

            if (!m_application.User.Identity.IsAuthenticated)
            {
                // Failed to authenticate user.
                Redirect(HttpStatusCode.Unauthorized);
            }

            if (IsAccessRestricted() ||
                !SecurityProviderUtility.IsResourceAccessible(resource, securityPrincipal))
            {
                // User does not have access to the resource.
                Redirect(HttpStatusCode.Forbidden);
            }
        }
Exemplo n.º 17
0
        public void Configuration(IAppBuilder app)
        {
            app.Use((context, next) =>
            {
                context.Response.Headers.Remove("Server");
                return(next.Invoke());
            });

            app.UseStageMarker(PipelineStage.PostAcquireState);

            // Modify the JSON serializer to serialize dates as UTC - otherwise, timezone will not be appended
            // to date strings and browsers will select whatever timezone suits them
            JsonSerializerSettings settings = JsonUtility.CreateDefaultSerializerSettings();

            settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;

            JsonSerializer serializer = JsonSerializer.Create(settings);

            GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);

            // Load security hub in application domain before establishing SignalR hub configuration
            using (new SecurityHub()) { }

            // Enable GSF role-based security authentication w/o Logon Page
            // Configuration Windows Authentication for self-hosted web service
            HttpListener listener = (HttpListener)app.Properties["System.Net.HttpListener"];

            listener.AuthenticationSchemeSelectorDelegate = AuthenticationSchemeForClient;
            app.Use((context, next) =>
            {
                string username = context.Request.User?.Identity.Name;

                if ((object)username == null)
                {
                    return(null);
                }

                // Get the principal used for verifying the user's pass-through authentication
                IPrincipal passthroughPrincipal = context.Request.User;

                // Create the security provider that will verify the user's pass-through authentication
                ISecurityProvider securityProvider = SecurityProviderCache.CreateProvider(username, passthroughPrincipal, false);
                securityProvider.Authenticate();

                // Return the security principal that will be used for role-based authorization
                SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);
                context.Request.User = new SecurityPrincipal(securityIdentity);

                return(next.Invoke());
            });


            HubConfiguration  hubConfig  = new HubConfiguration();
            HttpConfiguration httpConfig = new HttpConfiguration();

            // Enabled detailed client errors
            hubConfig.EnableDetailedErrors = true;

            // Enable GSF session management
            //httpConfig.EnableSessions(AuthenticationOptions);

            // Enable GSF role-based security authentication with Logon Page
            //app.UseAuthentication(AuthenticationOptions);



            string allowedDomainList = ConfigurationFile.Current.Settings["systemSettings"]["AllowedDomainList"]?.Value;

            if (allowedDomainList == "*")
            {
                app.UseCors(CorsOptions.AllowAll);
            }
            else if ((object)allowedDomainList != null)
            {
                httpConfig.EnableCors(new System.Web.Http.Cors.EnableCorsAttribute(allowedDomainList, "*", "*"));
            }


            // Load ServiceHub SignalR class
            app.MapSignalR(hubConfig);

            // Set configuration to use reflection to setup routes
            httpConfig.MapHttpAttributeRoutes(new CustomDirectRouteProvider());

            // Load the WebPageController class and assign its routes
            app.UseWebApi(httpConfig);

            // Setup resolver for web page controller instances
            app.UseWebPageController(WebServer.Default, Program.Host.DefaultWebPage, Program.Host.Model, typeof(AppModel) /*, AuthenticationOptions*/);

            httpConfig.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            // Check for configuration issues before first request
            httpConfig.EnsureInitialized();
        }
Exemplo n.º 18
0
        /// <summary>
        /// Logins the user.
        /// </summary>
        /// <param name="sender">Source of this event.</param>
        /// <param name="e">Arguments of this event.</param>
        protected void LoginButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Initialize the security provider.
                ISecurityProvider provider = SecurityProviderUtility.CreateProvider(LoginUsername.Text);

                if (provider.Authenticate(LoginPassword.Text))
                {
                    // Credentials were authenticated successfully.
                    SecurityProviderCache.CurrentProvider = provider;
                    if (RememberUsername.Checked)
                    {
                        Response.Cookies[CookieName][UsernameKey] = LoginUsername.Text;
                        Response.Cookies[CookieName].Expires      = DateTime.Now.AddYears(1);
                    }
                    else
                    {
                        Response.Cookies[CookieName][UsernameKey] = string.Empty;
                        Response.Cookies[CookieName].Expires      = DateTime.Now.AddYears(-1);
                    }

                    // Redirect to the referring page.
                    Response.Redirect(GetReferrerUrl(), false);
                }
                else
                {
                    // Check why authentication failed.
                    if (provider.UserData.PasswordChangeDateTime != DateTime.MinValue &&
                        provider.UserData.PasswordChangeDateTime <= DateTime.UtcNow)
                    {
                        // User must change password.
                        if (provider.CanChangePassword)
                        {
                            Response.Redirect(GetRedirectUrl(PasswordChangeStatusCode), false);
                        }
                        else
                        {
                            ShowMessage("Account password has expired.", true);
                        }
                    }
                    else
                    {
                        // Show why login failed.
                        if (!ShowFailureReason(provider))
                        {
                            ShowMessage("Authentication was not successful.", true);
                        }
                    }
                }
            }
            catch (SecurityException ex)
            {
                // Show security related error messages.
                ShowMessage(ex.Message.EnsureEnd('.'), true);
            }
            catch (Exception ex)
            {
                // Show ambiguous message for other errors.
                ShowMessage("Login failed due to an unexpected error.", true);
                System.Diagnostics.Trace.WriteLine(string.Format("Login error: \r\n  {0}", ex));
            }
            finally
            {
                LoginPassword.Focus();
            }
        }
Exemplo n.º 19
0
        private void SecureWindow_Initialized(object sender, EventArgs e)
        {
            // Don't proceed if the window is opened in design mode
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }

            // Check if the resource is excluded from being secured
            string resource = GetResourceName();

            if (ResourceAccessiblity != ResourceAccessiblityMode.AlwaysIncluded &&
                (ResourceAccessiblity == ResourceAccessiblityMode.AlwaysExcluded ||
                 !SecurityProviderUtility.IsResourceSecurable(resource)))
            {
                return;
            }

            try
            {
                // Setup the security provider for role-based security
                ISecurityProvider securityProvider = SecurityProviderCache.CreateProvider(WindowsIdentity.GetCurrent().Name);
                securityProvider.PassthroughPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                securityProvider.Authenticate();

                SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);
                SecurityPrincipal = new SecurityPrincipal(securityIdentity);
            }
            catch (Exception ex)
            {
                ShowSecurityDialog(DisplayType.AccessDenied, "Error loading security provider: " + ex.Message);
                return;
            }

            // Verify that the security principal has been authenticated
            if (!SecurityPrincipal.Identity.IsAuthenticated || ForceLoginDisplay)
            {
                ISecurityProvider securityProvider = SecurityPrincipal.Identity.Provider;

                // See if user's password has expired
                if (securityProvider.UserData.IsDefined && securityProvider.UserData.PasswordChangeDateTime <= DateTime.UtcNow)
                {
                    ShowSecurityDialog(DisplayType.ChangePassword, string.Format("Your password has expired. {0} You must change your password to continue.", securityProvider.AuthenticationFailureReason));
                }
                else
                {
                    ShowSecurityDialog(DisplayType.Login);
                }
            }

            // Perform a top-level permission check on the resource being accessed
            if (!string.IsNullOrEmpty(resource))
            {
                // Stay in a dialog display loop until either access to resource is available or user exits
                while (!m_shutdownRequested && !IsResourceAccessible(resource))
                {
                    // Access to resource is denied
                    ShowSecurityDialog(DisplayType.AccessDenied);
                }
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Attempts to change user's password.
        /// </summary>
        /// <param name="sender">Source of this event.</param>
        /// <param name="e">Arguments of this event.</param>
        private void ButtonChange_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Check if old and new password are different
                if (TextBoxOldPassword.Password == TextBoxNewPassword.Password)
                {
                    throw new Exception("New password cannot be same as old password.");
                }

                // Check is new password and confirm password are same
                if (TextBoxNewPassword.Password != TextBoxConfirmPassword.Password)
                {
                    throw new Exception("New password and confirm password should be same.");
                }

                ISecurityProvider securityProvider = SecurityProviderCache.CreateProvider(TextBoxChangePasswordUserName.Text);
                securityProvider.SecurePassword = TextBoxNewPassword.SecurePassword;

                if (securityProvider.CanChangePassword)
                {
                    // Attempt to change password
                    if (securityProvider.ChangePassword(TextBoxOldPassword.Password, TextBoxNewPassword.Password) &&
                        securityProvider.Authenticate())
                    {
                        // Password changed and authenticated successfully
                        DisplayErrorMessage("Password changed successfully.");

                        // Setup security principal for subsequent uses
                        SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);
                        SecurityPrincipal = new SecurityPrincipal(securityIdentity);
                        ClearErrorMessage();
                        ExitSuccess = true;
                    }
                    else
                    {
                        // Show why password change failed
                        if (!ShowFailureReason(securityProvider))
                        {
                            if (!securityProvider.IsUserAuthenticated)
                            {
                                DisplayErrorMessage("Authentication was not successful.");
                            }
                            else
                            {
                                DisplayErrorMessage("Password change was not successful.");
                            }

                            if (string.IsNullOrWhiteSpace(TextBoxChangePasswordUserName.Text))
                            {
                                TextBoxChangePasswordUserName.Focus();
                            }
                            else
                            {
                                TextBoxOldPassword.Focus();
                            }
                        }
                    }
                }
                else
                {
                    DisplayErrorMessage("Account does not support password change.");
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage("Change password failed: " + ex.Message);
                TextBoxOldPassword.Focus();
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Evaluates the <paramref name="evaluationContext"/> and initializes security.
        /// </summary>
        /// <param name="evaluationContext">An <see cref="EvaluationContext"/> object.</param>
        /// <param name="state">Custom state of the <see cref="SecurityPolicy"/>.</param>
        /// <returns></returns>
        public virtual bool Evaluate(EvaluationContext evaluationContext, ref object state)
        {
            // In order for this to work properly security on the binding must be configured to use windows security.
            // When this is done the caller's windows identity is available to us here and can be used to derive from
            // it the security principal that can be used by WCF service code downstream for implementing security.
            object property;

            if (evaluationContext.Properties.TryGetValue("Identities", out property))
            {
                // Extract and assign the caller's windows identity to current thread if available.
                IList <IIdentity> identities = property as List <IIdentity>;

                if ((object)identities == null)
                {
                    throw new SecurityException(string.Format("Null Identities in Evaluation Context for '{0}'", Thread.CurrentPrincipal.Identity));
                }

                foreach (IIdentity identity in identities)
                {
                    if (identity is WindowsIdentity)
                    {
                        Thread.CurrentPrincipal = new WindowsPrincipal((WindowsIdentity)identity);
                        break;
                    }
                }
            }

            string resource = GetResourceName();

            if (SecurityProviderUtility.IsResourceSecurable(resource))
            {
                // Initialize the security principal from caller's windows identity if uninitialized.
                ISecurityProvider securityProvider = SecurityProviderCache.CreateProvider(Thread.CurrentPrincipal.Identity.Name);
                securityProvider.PassthroughPrincipal = Thread.CurrentPrincipal;
                securityProvider.Authenticate();

                // Set up the security principal to provide role-based security.
                SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);
                Thread.CurrentPrincipal = new SecurityPrincipal(securityIdentity);

                // Setup the principal to be attached to the thread on which WCF service will execute.
                evaluationContext.Properties["Principal"] = Thread.CurrentPrincipal;

                // Verify that the current thread principal has been authenticated.
                if (!Thread.CurrentPrincipal.Identity.IsAuthenticated)
                {
                    throw new SecurityException(string.Format("Authentication failed for user '{0}'", Thread.CurrentPrincipal.Identity.Name));
                }

                // Perform a top-level permission check on the resource being accessed.
                if (!SecurityProviderUtility.IsResourceAccessible(resource, Thread.CurrentPrincipal))
                {
                    throw new SecurityException(string.Format("Access to '{0}' is denied", resource));
                }

                return(true);
            }

            // Setup the principal to be attached to the thread on which WCF service will execute.
            evaluationContext.Properties["Principal"] = Thread.CurrentPrincipal;

            return(true);
        }