// 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)); }
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); } }
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); } }
// 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)); }
// 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)); }
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); } }
/// <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(); } }
/// <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(); } } }
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); } } }
/// <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); }
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(); }