public void TestInvalidLoginAttemptCount() { var dataPersistence = ApplicationContext.Current.GetService <IDataPersistenceService <SecurityUser> >(); IIdentityProviderService provider = ApplicationContext.Current.GetService <IIdentityProviderService>(); // Reset data for test var user = dataPersistence.Query(u => u.UserName == "*****@*****.**", null).First(); user.Lockout = null; user.LastLoginTime = null; user.InvalidLoginAttempts = 0; dataPersistence.Update(user, provider.Authenticate("*****@*****.**", "password"), TransactionMode.Commit); try { var principal = provider.Authenticate("*****@*****.**", "passwordz"); Assert.Fail("Should throw SecurityException"); } catch (AuthenticationException) { // We should have a lockout user = dataPersistence.Get(user.Id(), null, false); Assert.AreEqual(1, user.InvalidLoginAttempts); Assert.AreEqual(null, user.LastLoginTime); Assert.IsFalse(user.Lockout.HasValue); } }
public void TestAuthenticateLockout() { //var dataPersistence = ApplicationServiceContext.Current.GetService<IDataPersistenceService<SecurityUser>>(); IIdentityProviderService provider = ApplicationServiceContext.Current.GetService <IIdentityProviderService>(); // Reset data for test //var user = dataPersistence.Query(u => u.UserName == "*****@*****.**", null).First(); //user.Lockout = null; // user.LastLoginTime = null; //user.InvalidLoginAttempts = 0; //dataPersistence.Update(user, TransactionMode.Commit); // Try 4 times to log in for (int i = 0; i < 7; i++) { try { var principal = provider.Authenticate("*****@*****.**", "passwordz"); Assert.Fail("Should throw SecurityException"); } catch (AuthenticationException) { } } // We should have a lockout //user = dataPersistence.Get(user.Id(), null, false); //Assert.IsTrue(user.InvalidLoginAttempts >= 4); //Assert.AreEqual(null, user.LastLoginTime); //Assert.IsTrue(user.Lockout.HasValue); }
public void ClassSetup() { AuthenticationContext.EnterSystemContext(); IIdentityProviderService identityProvider = ApplicationServiceContext.Current.GetService <IIdentityProviderService>(); var identity = identityProvider.CreateIdentity(nameof(SecurityRolePersistenceServiceTest), "password", AuthenticationContext.Current.Principal); // Give this identity the administrative functions group IRoleProviderService roleProvider = ApplicationServiceContext.Current.GetService <IRoleProviderService>(); roleProvider.AddUsersToRoles(new string[] { identity.Name }, new string[] { "ADMINISTRATORS" }, AuthenticationContext.Current.Principal); // Authorize s_authorization = identityProvider.Authenticate(nameof(SecurityRolePersistenceServiceTest), "password"); IDataPersistenceService <SecurityPolicy> policyService = ApplicationServiceContext.Current.GetService <IDataPersistenceService <SecurityPolicy> >(); s_chickenCostumePolicy = new SecurityPolicy() { Name = "Allow wearing of chicken costume", Oid = "2.3.23.543.25.2" }; s_chickenCostumePolicy = policyService.Insert(s_chickenCostumePolicy, TransactionMode.Commit, s_authorization); }
public static void ClassSetup(TestContext context) { AppDomain.CurrentDomain.SetData( "DataDirectory", Path.Combine(context.TestDeploymentDir, string.Empty)); IIdentityProviderService identityProvider = ApplicationContext.Current.GetService <IIdentityProviderService>(); var identity = identityProvider.CreateIdentity(nameof(SecurityRolePersistenceServiceTest), "password", AuthenticationContext.SystemPrincipal); // Give this identity the administrative functions group IRoleProviderService roleProvider = ApplicationContext.Current.GetService <IRoleProviderService>(); roleProvider.AddUsersToRoles(new string[] { identity.Name }, new string[] { "ADMINISTRATORS" }, AuthenticationContext.SystemPrincipal); // Authorize s_authorization = identityProvider.Authenticate(nameof(SecurityRolePersistenceServiceTest), "password"); IDataPersistenceService <SecurityPolicy> policyService = ApplicationContext.Current.GetService <IDataPersistenceService <SecurityPolicy> >(); s_chickenCostumePolicy = new SecurityPolicy() { Name = "Allow wearing of chicken costume", Oid = "2.3.23.543.25.2" }; s_chickenCostumePolicy = policyService.Insert(s_chickenCostumePolicy, s_authorization, TransactionMode.Commit); }
public void TestAuthenticateSuccess() { IIdentityProviderService provider = ApplicationServiceContext.Current.GetService <IIdentityProviderService>(); var principal = provider.Authenticate("*****@*****.**", "password"); Assert.AreEqual("*****@*****.**", principal.Identity.Name); Assert.IsTrue(principal.Identity.IsAuthenticated); Assert.AreEqual("LOCAL", principal.Identity.AuthenticationType); }
/// <summary> /// Authenticate using the authentication provider /// </summary> internal bool Authenticate(IIdentityProviderService authenticationProvider, IRestClient context) { bool retVal = false; while (!retVal) { Console.WriteLine("Access denied, authentication required."); if (String.IsNullOrEmpty(this.m_configuration.User)) { Console.Write("Username:"******"Username:{0}", this.m_configuration.User); } if (String.IsNullOrEmpty(this.m_configuration.Password)) { this.m_configuration.Password = DisplayUtil.PasswordPrompt("Password:"******"Password:{0}", new String('*', this.m_configuration.Password.Length * 2)); } // Now authenticate try { var principal = (authenticationProvider as OAuthIdentityProvider)?.Authenticate( new SanteDBClaimsPrincipal(new SanteDBClaimsIdentity(this.m_configuration.User, false, "OAUTH2")), this.m_configuration.Password) ?? authenticationProvider.Authenticate(this.m_configuration.User, this.m_configuration.Password); if (principal != null) { retVal = true; AuthenticationContext.Current = new AuthenticationContext(principal); } else { this.m_configuration.Password = null; } } catch (Exception e) { this.m_tracer.TraceError("Authentication error: {0}", e.Message); this.m_configuration.Password = null; } } return(retVal); }
public void TestChangePassword() { // var dataPersistence = ApplicationServiceContext.Current.GetService<IDataPersistenceService<SecurityUser>>(); IIdentityProviderService identityProvider = ApplicationServiceContext.Current.GetService <IIdentityProviderService>(); //var user = dataPersistence.Query(u => u.UserName == "*****@*****.**", null).First(); // var existingPassword = user.PasswordHash; // Now change the password var principal = identityProvider.Authenticate("*****@*****.**", "password"); identityProvider.ChangePassword("*****@*****.**", "newpassword", principal); principal = identityProvider.Authenticate("*****@*****.**", "newpassword"); identityProvider.ChangePassword("*****@*****.**", "password", principal); //user = dataPersistence.Get(user.Id(), principal, false); //Assert.AreNotEqual(existingPassword, user.PasswordHash); // Change the password back //user.PasswordHash = existingPassword; //dataPersistence.Update(user, principal, TransactionMode.Commit); }
public void TestAuthenticateFailure() { try { IIdentityProviderService provider = ApplicationServiceContext.Current.GetService <IIdentityProviderService>(); var principal = provider.Authenticate("*****@*****.**", "passwordz"); Assert.Fail("Should throw SecurityException"); } catch (AuthenticationException) { } }
public static void ClassSetup(TestContext context) { AppDomain.CurrentDomain.SetData( "DataDirectory", Path.Combine(context.TestDeploymentDir, string.Empty)); IIdentityProviderService identityProvider = ApplicationContext.Current.GetService <IIdentityProviderService>(); var identity = identityProvider.CreateIdentity(nameof(SqlRoleProviderTest), "password", AuthenticationContext.SystemPrincipal); // Give this identity the administrative functions group IRoleProviderService roleProvider = ApplicationContext.Current.GetService <IRoleProviderService>(); roleProvider.AddUsersToRoles(new string[] { identity.Name }, new string[] { "ADMINISTRATORS" }, AuthenticationContext.SystemPrincipal); // Authorize s_authorization = identityProvider.Authenticate(nameof(SqlRoleProviderTest), "password"); }
/// <summary> /// Authenticate using the authentication provider /// </summary> internal bool Authenticate(IIdentityProviderService authenticationProvider, IRestClient context) { bool retVal = false; while (!retVal) { Console.WriteLine("Access denied, authentication required."); if (String.IsNullOrEmpty(this.m_configuration.User)) { Console.Write("Username:"******"Username:{0}", this.m_configuration.User); } if (String.IsNullOrEmpty(this.m_configuration.Password)) { Console.Write("Password:"******" \b"); } else { Console.CursorLeft = Console.CursorLeft + 1; } } else if (c == ConsoleKey.Escape) { return(false); } else if (c != ConsoleKey.Enter) { passwd.Append(ki.KeyChar); Console.Write("\b*"); } } this.m_configuration.Password = passwd.ToString(); Console.WriteLine(); } else { Console.WriteLine("Password:{0}", new String('*', this.m_configuration.Password.Length * 2)); } // Now authenticate try { var principal = (authenticationProvider as OAuthIdentityProvider)?.Authenticate( new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity(this.m_configuration.User, "RQO"), new Claim[] { new Claim(OpenIzClaimTypes.OpenIzScopeClaim, context.Description.Endpoint[0].Address) }, "OAUTH2", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType)), this.m_configuration.Password) ?? authenticationProvider.Authenticate(this.m_configuration.User, this.m_configuration.Password); if (principal != null) { retVal = true; AuthenticationContext.Current = new AuthenticationContext(principal); } else { this.m_configuration.Password = null; } } catch (Exception e) { this.m_tracer.TraceError("Authentication error: {0}", e.Message); this.m_configuration.Password = null; } } return(retVal); }
/// <summary> /// OAuth token request /// </summary> // TODO: Add ability to authentication a claim with POU public Stream Token(Message incomingMessage) { // Convert inbound data to token request // HACK: This is to overcome WCF's lack of easy URL encoded form processing // Why use WCF you ask? Well, everything else is hosted in WCF and we // want to be able to use the same ports as our other services. Could find // no documentation about running WCF and WepAPI stuff in the same app domain // on the same ports NameValueCollection tokenRequest = new NameValueCollection(); XmlDictionaryReader bodyReader = incomingMessage.GetReaderAtBodyContents(); bodyReader.ReadStartElement("Binary"); String rawBody = Encoding.UTF8.GetString(bodyReader.ReadContentAsBase64()); var parms = rawBody.Split('&'); foreach (var p in parms) { var kvp = p.Split('='); tokenRequest.Add(kvp[0], kvp[1].Replace('+', ' '). Replace("%3A", ":"). Replace("%2F", "/"). Replace("%3C", "<"). Replace("%3E", ">"). Replace("%21", "!"). Replace("%3D", "="). Replace("%5B", "["). Replace("%5D", "]").Trim()); } // Get the client application IApplicationIdentityProviderService clientIdentityService = ApplicationContext.Current.GetService <IApplicationIdentityProviderService>(); IIdentityProviderService identityProvider = ApplicationContext.Current.GetService <IIdentityProviderService>(); // Only password grants if (tokenRequest["grant_type"] != OAuthConstants.GrantNamePassword && tokenRequest["grant_type"] != OAuthConstants.GrantNameRefresh) { return(this.CreateErrorCondition(OAuthErrorType.unsupported_grant_type, "Only 'password' or 'refresh_token' grants allowed")); } // Password grant needs well formed scope Uri scope = null; if (String.IsNullOrWhiteSpace(tokenRequest["scope"]) || !Uri.TryCreate(tokenRequest["scope"], UriKind.Absolute, out scope)) { this.m_traceSource.TraceEvent(TraceEventType.Warning, 0, "Scope:{0} is not well formed", tokenRequest["scope"]); return(this.CreateErrorCondition(OAuthErrorType.invalid_scope, "Password grant must have well known scope")); } IPrincipal clientPrincipal = ClaimsPrincipal.Current; // Client is not authenticated if (clientPrincipal == null || !clientPrincipal.Identity.IsAuthenticated) { return(this.CreateErrorCondition(OAuthErrorType.unauthorized_client, "Unauthorized Client")); } this.m_traceSource.TraceInformation("Begin owner password credential grant for {0}", clientPrincipal.Identity.Name); if (this.m_configuration.AllowedScopes != null && !this.m_configuration.AllowedScopes.Contains(tokenRequest["scope"])) { return(this.CreateErrorCondition(OAuthErrorType.invalid_scope, "Scope not registered with provider")); } var appliesTo = new EndpointReference(tokenRequest["scope"]); // Validate username and password if (String.IsNullOrWhiteSpace(tokenRequest["username"]) && String.IsNullOrWhiteSpace(tokenRequest["refresh_token"])) { return(this.CreateErrorCondition(OAuthErrorType.invalid_request, "Invalid client grant message")); } else { try { IPrincipal principal = null; // Is there a TFA secret if (tokenRequest["grant_type"] == OAuthConstants.GrantNamePassword) { if (WebOperationContext.Current.IncomingRequest.Headers[OAuthConstants.TfaHeaderName] != null) { principal = identityProvider.Authenticate(tokenRequest["username"], tokenRequest["password"], WebOperationContext.Current.IncomingRequest.Headers[OAuthConstants.TfaHeaderName]); } else { principal = identityProvider.Authenticate(tokenRequest["username"], tokenRequest["password"]); } } else if (tokenRequest["grant_type"] == OAuthConstants.GrantNameRefresh && identityProvider is IIdentityRefreshProviderService) { var refreshToken = tokenRequest["refresh_token"]; // Verify signature! var signingCredentials = this.CreateSigningCredentials(); var signer = new JwtSecurityTokenHandler().SignatureProviderFactory.CreateForVerifying(signingCredentials.SigningKey, signingCredentials.SignatureAlgorithm); // Verify var tokenParts = refreshToken.Split('.').Select(o => Enumerable.Range(0, o.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(o.Substring(x, 2), 16)) .ToArray() ).ToArray(); if (tokenParts.Length != 2) { throw new SecurityTokenException("Refresh token in invalid format"); } else if (!signer.Verify(tokenParts[1], tokenParts[0])) { throw new SecurityTokenValidationException("Signature does not match refresh token data"); } else { var secret = tokenParts[1]; principal = (identityProvider as IIdentityRefreshProviderService).Authenticate(secret); } } else { throw new InvalidOperationException("Invalid grant type"); } if (principal == null) { return(this.CreateErrorCondition(OAuthErrorType.invalid_grant, "Invalid username or password")); } else { var clams = this.ValidateClaims(principal); return(this.CreateTokenResponse(principal, clientPrincipal, appliesTo, this.ValidateClaims(principal))); } } catch (AuthenticationException e) { this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, "Error generating token: {0}", e); return(this.CreateErrorCondition(OAuthErrorType.invalid_grant, e.Message)); } catch (SecurityException e) { this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, "Error generating token: {0}", e); return(this.CreateErrorCondition(OAuthErrorType.invalid_grant, e.Message)); } catch (Exception e) { this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, "Error generating token: {0}", e); return(this.CreateErrorCondition(OAuthErrorType.invalid_request, e.Message)); } } }