コード例 #1
0
 public void ChangeStatusTask(ITask[] tasks, SecurityIdentity securityObject, TaskStatus @enum)
 {
     foreach (var task in tasks)
     {
         finishTask(task, securityObject, @enum);
     }
 }
コード例 #2
0
        /// <summary>
        /// Ad-ba kérés sokáig tarthat. Azért van először külön beszúrás majd AD-ba hívás után entitás frissítés.
        /// </summary>
        /// <param name="identifier"></param>
        public SecurityIdentity RegisterUserIfNotExists(string identifier)
        {
            var identity = secObjectRepository.GetAll()
                           .OfType <SecurityIdentity>()
                           .Include(x => x.GroupMemberShips)
                           .ThenInclude(x => x.Group)
                           .Where(x => x.Identifier.Equals(identifier)).SingleOrDefault();

            if (identity == null)
            {
                var newUser = new SecurityIdentity
                {
                    Identifier = identifier
                };
                secObjectRepository.Add(newUser);
                secObjectRepository.SaveChanges();

                using (var adHandler = new UserRegisterFromAd())
                {
                    var result = adHandler.GetADUser(identifier.Replace("MVMH\\", ""));

                    newUser.Email    = result.EmailAddress;
                    newUser.FullName = result.Name;

                    secObjectRepository.Update(newUser);
                    secObjectRepository.SaveChanges();

                    return(newUser);
                }
            }
            else
            {
                return(identity);
            }
        }
コード例 #3
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));
        }
コード例 #4
0
        private void buttonRemove_Click(object sender, EventArgs e)
        {
            if (this.listUsersAndGroups.SelectedItem != null)
            {
                SecurityIdentity sid = (SecurityIdentity)this.listUsersAndGroups.SelectedItem;

                List <AccessControlEntry> toDelete = new List <AccessControlEntry>();

                foreach (AccessControlEntry ace in this.acl)
                {
                    if (ace.AccountSID == sid)
                    {
                        toDelete.Add(ace);
                    }
                }

                foreach (AccessControlEntry deleteAce in toDelete)
                {
                    this.acl.Remove(deleteAce);
                }

                this.userList.Remove(sid);

                this.listUsersAndGroups.Items.Remove(sid);
            }
        }
コード例 #5
0
 public virtual void ChangeStatus(SecurityIdentity approvedBy, TaskStatus newTaskStatus)
 {
     // need this because of group approval logic
     ApprovedAt = DateTime.Now;
     Status     = newTaskStatus;
     ApprovedBySecurityIdentityID = approvedBy.Id;
 }
コード例 #6
0
        private void ButtonAdd_Click(object sender, EventArgs e)
        {
            if (InputBox.Show("Add User or Group", "Enter the User or Group Name:", out var accountName) == DialogResult.OK)
            {
                try
                {
                    var sid = SecurityIdentity.SecurityIdentityFromName(accountName);

                    if (MessageBox.Show(string.Format("Add user or group: {0}?", sid.Name), "User or Group Found", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        if (!userList.Contains(sid))
                        {
                            var ace = new AccessControlEntry(sid)
                            {
                                AceType = AceType.AccessAllowed
                            };
                            acl.Add(ace);
                            userList.Add(sid);
                            ListUsersAndGroups.Items.Add(sid);

                            ListUsersAndGroups.SelectedItem = sid;
                        }
                        else
                        {
                            MessageBox.Show("The selected user or group already exists.", "Duplicate User or Group", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("User or group name was not found. " + ex.Message, "User or Group Not Found", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
コード例 #7
0
        private void SecureSampleDB(SecureDatabase db)
        {
            SecurityPermissions security = db.Security(sampleTableName);

            security.RestrictedColumns.Add(SecurityIdentity.Create(IdentityScope.Group, "G1"), new List <string>(new string[] { "SecretOwner" }));
            security.RestrictedColumns.Add(SecurityIdentity.Create(IdentityScope.Group, "G2"), new List <string>(new string[] { "SecretPriority" }));
            security.RowRestrictedUsers.Add(SecurityIdentity.Create(IdentityScope.Group, "G3"), "SecretPriority > 1");
            security.RowRestrictedUsers.Add(SecurityIdentity.Create(IdentityScope.Group, "G4"), "SecretPriority > 2");
        }
コード例 #8
0
 public static ExternalUser CreateExternalUserForGroupMailbox(string externalUserName, string externalUserId, Guid mailboxGuid, SecurityIdentity.GroupMailboxMemberType groupMailboxMemberType)
 {
     return(new ExternalUser(new MemoryPropertyBag())
     {
         Name = externalUserName,
         ExternalId = externalUserId,
         SmtpAddress = SmtpAddress.Parse(externalUserId),
         Sid = SecurityIdentity.GetGroupSecurityIdentifier(mailboxGuid, groupMailboxMemberType)
     });
 }
コード例 #9
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);
            }
        }
コード例 #10
0
        public async Task GrantPermissionsAsync(PermissionScope scope, IdentityScope identityType, string identity)
        {
            var resp = await _client.SendObjectAsync(
                HttpMethod.Post,
                String.Format("table/{0}/permissions/{1}", _tableName, scope.ToString().ToLowerInvariant()),
                value : SecurityIdentity.Create(identityType, identity));

            await resp.EnsureArribaSuccess();

            return;
        }
コード例 #11
0
 protected bool IsInIdentity(IPrincipal currentUser, SecurityIdentity targetUserOrGroup)
 {
     if (targetUserOrGroup.Scope == IdentityScope.User)
     {
         return(targetUserOrGroup.Name.Equals(currentUser.Identity.Name, StringComparison.OrdinalIgnoreCase));
     }
     else
     {
         return(_claimsAuth.IsUserInGroup(currentUser, targetUserOrGroup.Name));
     }
 }
コード例 #12
0
ファイル: SecurityService.svc.cs プロジェクト: sotaria/gsf
        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);
            }
        }
コード例 #13
0
        protected void Application_PostAuthenticateRequest()
        {
            HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

            if (authCookie != null)
            {
                FormsAuthenticationTicket ticket    = FormsAuthentication.Decrypt(authCookie.Value);
                JavaScriptSerializer      js        = new JavaScriptSerializer();
                UserSecurityRole          user      = js.Deserialize <UserSecurityRole>(ticket.UserData);
                SecurityIdentity          identity  = new SecurityIdentity(user);
                SecurityPrinciple         principle = new SecurityPrinciple(identity);
                HttpContext.Current.User = principle;
            }
        }
コード例 #14
0
ファイル: SecurityService.svc.cs プロジェクト: sotaria/gsf
        /// <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);
        }
コード例 #15
0
 public static SidBinaryAndAttributes[] GetGroupMailboxSidBinaryAndAttributes(Guid groupMailboxGuid, SecurityIdentity.GroupMailboxMemberType groupMailboxMemberType)
 {
     SidBinaryAndAttributes[] result = null;
     try
     {
         SecurityIdentifier groupSecurityIdentifier = SecurityIdentity.GetGroupSecurityIdentifier(groupMailboxGuid, groupMailboxMemberType);
         result = new SidBinaryAndAttributes[]
         {
             new SidBinaryAndAttributes(groupSecurityIdentifier, 4U)
         };
     }
     catch (ArgumentException arg)
     {
         GroupMailboxAuthorizationHandler.Tracer.TraceError <Guid, SecurityIdentity.GroupMailboxMemberType, ArgumentException>(0L, "Unable to construct SidBinaryAndAttributes for group mailbox {0} and user type {1} : {2}", groupMailboxGuid, groupMailboxMemberType, arg);
         throw new ObjectNotFoundException(ServerStrings.GroupMailboxAccessSidConstructionFailed(groupMailboxGuid, groupMailboxMemberType.ToString()));
     }
     return(result);
 }
コード例 #16
0
        public SecurityIdentity RegisterUserIfNotExists(string identifier)
        {
            var identity = RlsIdentityRepo.Find(x => x.Identifier.Equals(identifier)).SingleOrDefault();

            if (identity == null)
            {
                var newUser = new SecurityIdentity
                {
                    Identifier = identifier
                };
                RlsIdentityRepo.Add(newUser);
                RlsIdentityRepo.SaveChanges();

                return(newUser);
            }
            else
            {
                return(identity);
            }
        }
コード例 #17
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));
        }
コード例 #18
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));
        }
コード例 #19
0
        private static SecurityIdentity ParseIdentity(string identity)
        {
            string[] parts = identity.Split(new char[] { ':' });
            if (parts.Length != 2)
            {
                throw new ArgumentException(String.Format(IdentityFormatExceptionFormatString, identity));
            }

            switch (parts[0].ToLowerInvariant())
            {
            case "u":
            case "user":
                return(SecurityIdentity.Create(IdentityScope.User, parts[1]));

            case "g":
            case "group":
                return(SecurityIdentity.Create(IdentityScope.Group, parts[1]));

            default:
                throw new ArgumentException(String.Format(IdentityFormatExceptionFormatString, identity));
            }
        }
コード例 #20
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);
        }
コード例 #21
0
ファイル: SecurityModule.cs プロジェクト: sotaria/gsf
        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);
            }
        }
コード例 #22
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();
            }
        }
コード例 #23
0
        /// <summary>
        /// Logins the user.
        /// </summary>
        /// <param name="sender">Source of this event.</param>
        /// <param name="e">Arguments of this event.</param>
        private void ButtonLogin_Click(object sender, RoutedEventArgs e)
        {
            UserInfo userInfo;
            WindowsImpersonationContext impersonationContext = null;
            ISecurityProvider           securityProvider;

            try
            {
                // Determine whether we need to try impersonating the user
                userInfo = new UserInfo(TextBoxUserName.Text);

                // If the application is unable to access the domain, possibly because the local user
                // running the application does not have access to domain objects, it's possible that
                // the user logging in does have access to the domain. So we attempt to impersonate the
                // user logging in to allow authentication to proceed
                if (!userInfo.DomainRespondsForUser && TryImpersonate(userInfo.LoginID, TextBoxPassword.Password, out impersonationContext))
                {
                    try
                    {
                        // Working around a known issue - DirectorySearcher will often throw
                        // an exception the first time it is used after impersonating another
                        // user so we get that out of the way here
                        userInfo.Initialize();
                    }
                    catch (InitializationException)
                    {
                        // Exception is expected so we ignore it
                    }
                }

                // Initialize the security provider
                securityProvider = SecurityProviderCache.CreateProvider(TextBoxUserName.Text);
                securityProvider.SecurePassword = TextBoxPassword.SecurePassword;

                // Attempt to authenticate user
                if (securityProvider.Authenticate())
                {
                    // Setup security principal for subsequent uses
                    SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);
                    SecurityPrincipal = new SecurityPrincipal(securityIdentity);
                    ClearErrorMessage();
                    ExitSuccess = true;
                }
                else
                {
                    // Verify their password hasn't expired
                    if (securityProvider.UserData.IsDefined && securityProvider.UserData.PasswordChangeDateTime <= DateTime.UtcNow)
                    {
                        // Display password expired message
                        DisplayErrorMessage(string.Format("Your password has expired. {0} You must change your password to continue.", securityProvider.AuthenticationFailureReason));
                        m_displayType = DisplayType.ChangePassword;
                        ManageScreenVisualization();
                        TextBoxPassword.Password = "";
                    }
                    else
                    {
                        // Display login failure message
                        DisplayErrorMessage("The username or password is invalid. " + securityProvider.AuthenticationFailureReason);

                        if (string.IsNullOrWhiteSpace(TextBoxUserName.Text))
                        {
                            TextBoxUserName.Focus();
                        }
                        else
                        {
                            TextBoxPassword.Focus();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage("Login failed: " + ex.Message);

                if (string.IsNullOrWhiteSpace(TextBoxUserName.Text))
                {
                    TextBoxUserName.Focus();
                }
                else
                {
                    TextBoxPassword.Focus();
                }
            }
            finally
            {
                if ((object)impersonationContext != null)
                {
                    impersonationContext.Undo();
                    impersonationContext.Dispose();
                }
            }
        }
コード例 #24
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);
                }
            }
        }
コード例 #25
0
        /// <summary>
        /// Modifies the HTTP request message pipeline to include a session identifier.
        /// </summary>
        /// <param name="request">The HTTP request message to send to the server.</param>
        /// <param name="cancellationToken">A cancellation token to cancel operation.</param>
        /// <returns>HTTP response message.</returns>
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Get existing session data from the request, if any
            CookieHeaderValue cookie             = request.Headers.GetCookies(SessionToken).FirstOrDefault();
            string            sessionCookieValue = cookie?[SessionToken].Value;
            Guid sessionID;

            // If session ID format is invalid, create a new one
            if (!Guid.TryParse(sessionCookieValue, out sessionID))
            {
                sessionID = Guid.NewGuid();
            }

            sessionCookieValue = sessionID.ToString();

            // Save session ID (as Guid) in the request properties
            request.Properties[SessionToken] = sessionID;

            // Continue processing the HTTP request
            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

            // Store session ID in response message cookie
            response.Headers.AddCookies(new[] { new CookieHeaderValue(SessionToken, sessionCookieValue)
                                                {
                                                    Path = "/"
                                                } });

            // Get authentication options associated with this request
            ReadonlyAuthenticationOptions options = request.GetAuthenticationOptions();

            // If requesting the AuthTest page using BASIC authentication, reissue the client's authentication token
            string authTestPage = options.AuthTestPage;

            if (request.RequestUri.LocalPath == authTestPage)
            {
                SecurityPrincipal securityPrincipal = request.GetRequestContext().Principal as SecurityPrincipal;
                SecurityIdentity  securityIdentity  = securityPrincipal?.Identity;
                ISecurityProvider securityProvider  = securityIdentity?.Provider;

                string username = securityIdentity?.Name;
                string password = securityProvider?.Password;

                if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
                {
                    string authenticationToken = IssueAuthenticationToken(username, password);

                    InvalidateAuthenticationToken(request);

                    response.Headers.AddCookies(new[]
                    {
                        new CookieHeaderValue(AuthenticationToken, authenticationToken)
                        {
                            Path   = request.RequestUri.LocalPath,
                            MaxAge = TimeSpan.FromDays(30.0D)
                        }
                    });
                }

                // AuthTest page should always have a valid request verification token
                request.ValidateRequestVerificationToken(options);
            }

            return(response);
        }
コード例 #26
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 securityProvider = SecurityProviderUtility.CreateProvider(ChangePasswordUsername.Text);

                if (securityProvider.CanChangePassword)
                {
                    // Attempt to change password.
                    if (securityProvider.ChangePassword(ChangePasswordOldPassword.Text, ChangePasswordNewPassword.Text))
                    {
                        securityProvider.Password = ChangePasswordNewPassword.Text;

                        // Password changed successfully.
                        if (securityProvider.Authenticate())
                        {
                            // Password authenticated successfully.
                            SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);
                            Thread.CurrentPrincipal = new SecurityPrincipal(securityIdentity);
                            Response.Redirect(GetReferrerUrl(), false);
                        }
                        else
                        {
                            // Show why authentication failed.
                            if (!ShowFailureReason(securityProvider))
                            {
                                ShowMessage("Authentication was not successful.", true);
                            }
                        }
                    }
                    else
                    {
                        // Show why password change failed.
                        if (!ShowFailureReason(securityProvider))
                        {
                            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();
            }
        }
コード例 #27
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 securityProvider = SecurityProviderUtility.CreateProvider(LoginUsername.Text);
                securityProvider.Password = LoginPassword.Text;

                if (securityProvider.Authenticate())
                {
                    // Credentials were authenticated successfully.
                    SecurityIdentity securityIdentity = new SecurityIdentity(securityProvider);
                    Thread.CurrentPrincipal = new SecurityPrincipal(securityIdentity);

                    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 (securityProvider.UserData.PasswordChangeDateTime != DateTime.MinValue &&
                        securityProvider.UserData.PasswordChangeDateTime <= DateTime.UtcNow)
                    {
                        // User must change password.
                        if (securityProvider.CanChangePassword)
                        {
                            Response.Redirect(GetRedirectUrl(PasswordChangeStatusCode), false);
                        }
                        else
                        {
                            ShowMessage("Account password has expired.", true);
                        }
                    }
                    else
                    {
                        // Show why login failed.
                        if (!ShowFailureReason(securityProvider))
                        {
                            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();
            }
        }
コード例 #28
0
 private void finishTask(ITask task, SecurityIdentity securityObject, TaskStatus @enum)
 {
     task.Status = @enum;
     task.ChangeStatus(securityObject, @enum);
 }
コード例 #29
0
 public void ChangeStatusTask(ITask task, SecurityIdentity securityObject, TaskStatus @enum)
 {
     finishTask(task, securityObject, @enum);
 }
コード例 #30
0
ファイル: SecurityPolicy.cs プロジェクト: sotaria/gsf
        /// <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);
        }