/// <summary> /// Creates a new local security repository service /// </summary> public LocalSecurityRepository( IRepositoryService <SecurityUser> userRepository, IRepositoryService <SecurityApplication> applicationRepository, IRepositoryService <SecurityRole> roleRepository, IRepositoryService <SecurityDevice> deviceRepository, IRepositoryService <SecurityPolicy> policyRepository, IRepositoryService <UserEntity> userEntityRepository, IDataPersistenceService <SecurityProvenance> provenanceRepository, IRoleProviderService roleProviderService, IIdentityProviderService identityProviderService, IApplicationIdentityProviderService applicationIdentityProvider, IDeviceIdentityProviderService deviceIdentityProvider) { this.m_userRepository = userRepository; this.m_applicationIdentityProvider = applicationIdentityProvider; this.m_applicationRepository = applicationRepository; this.m_identityProviderService = identityProviderService; this.m_provenancePersistence = provenanceRepository; this.m_deviceIdentityProvider = deviceIdentityProvider; this.m_deviceRepository = deviceRepository; this.m_policyRepository = policyRepository; this.m_roleRepository = roleRepository; this.m_userEntityRepository = userEntityRepository; this.m_roleProvider = roleProviderService; }
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 TestAuthenticateLockout() { 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, AuthenticationContext.SystemPrincipal, 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 void TestInvalidLoginAttemptCount() { var dataPersistence = ApplicationServiceContext.Current.GetService <IDataPersistenceService <SecurityUser> >(); IIdentityProviderService provider = ApplicationServiceContext.Current.GetService <IIdentityProviderService>(); // Reset data for test //var user = provider..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); } }
/// <summary> /// Audit a login of a principal /// </summary> public static void AuditLogin(IPrincipal principal, String identityName, IIdentityProviderService identityProvider, bool successfulLogin = true) { if ((principal?.Identity?.Name ?? identityName) == ApplicationContext.Current.Configuration.GetSection <SecurityConfigurationSection>().DeviceName) { return; // don't worry about this } AuditData audit = new AuditData(DateTime.Now, ActionType.Execute, successfulLogin ? OutcomeIndicator.Success : OutcomeIndicator.EpicFail, EventIdentifierType.UserAuthentication, CreateAuditActionCode(EventTypeCodes.Login)); var configService = ApplicationContext.Current.Configuration.GetSection <SecurityConfigurationSection>(); audit.Actors.Add(new AuditActorData() { NetworkAccessPointType = NetworkAccessPointType.MachineName, NetworkAccessPointId = configService.DeviceName, UserName = principal?.Identity?.Name ?? identityName, UserIsRequestor = true, ActorRoleCode = (principal as ClaimsPrincipal)?.Claims.Where(o => o.Type == ClaimsIdentity.DefaultRoleClaimType).Select(o => new AuditCode(o.Value, "OizRoles")).ToList() }); AddDeviceActor(audit); audit.AuditableObjects.Add(new AuditableObject() { IDTypeCode = AuditableObjectIdType.Uri, NameData = identityProvider.GetType().AssemblyQualifiedName, ObjectId = $"http://openiz.org/mobile/auth/{identityProvider.GetType().FullName.Replace(".", "/")}", Type = AuditableObjectType.SystemObject, Role = AuditableObjectRole.Job }); AddAncillaryObject(audit); SendAudit(audit); }
public void TestUpdateValidSecurityUser() { IPasswordHashingService hashingService = ApplicationServiceContext.Current.GetService <IPasswordHashingService>(); SecurityUser userUnderTest = new SecurityUser() { Email = "*****@*****.**", EmailConfirmed = false, Password = hashingService.ComputeHash("password"), SecurityHash = "cert", UserName = "******", UserClass = UserClassKeys.HumanUser }; // Store user IIdentityProviderService identityService = ApplicationServiceContext.Current.GetService <IIdentityProviderService>(); var authContext = AuthenticationContext.SystemPrincipal; Assert.IsNotNull(authContext); var userAfterUpdate = base.DoTestUpdate(userUnderTest, "PhoneNumber", authContext); // Update Assert.IsNotNull(userAfterUpdate.UpdatedTime); Assert.IsNotNull(userAfterUpdate.PhoneNumber); Assert.AreEqual(authContext.Identity.Name, userAfterUpdate.LoadProperty <SecurityProvenance>("UpdatedBy").LoadProperty <SecurityUser>("User").UserName); }
/// <summary> /// Audit a login of a principal /// </summary> public static void AuditLogin(IPrincipal principal, String identityName, IIdentityProviderService identityProvider, bool successfulLogin = true) { traceSource.TraceVerbose("Create Login audit"); AuditData audit = new AuditData(DateTime.Now, ActionType.Execute, successfulLogin ? OutcomeIndicator.Success : OutcomeIndicator.EpicFail, EventIdentifierType.UserAuthentication, CreateAuditActionCode(EventTypeCodes.Login)); audit.Actors.Add(new AuditActorData() { NetworkAccessPointType = NetworkAccessPointType.MachineName, NetworkAccessPointId = Dns.GetHostName(), UserName = principal?.Identity?.Name ?? identityName, UserIsRequestor = true, ActorRoleCode = principal == null ? new List <AuditCode>() : ApplicationContext.Current.GetService <IRoleProviderService>()?.GetAllRoles(principal.Identity.Name).Select(o => new AuditCode(o, null) ).ToList() }); AddDeviceActor(audit); AddSenderDeviceActor(audit); audit.AuditableObjects.Add(new AuditableObject() { IDTypeCode = AuditableObjectIdType.Uri, NameData = identityProvider.GetType().AssemblyQualifiedName, ObjectId = $"http://openiz.org/auth/{identityProvider.GetType().FullName.Replace(".", "/")}", Type = AuditableObjectType.SystemObject, Role = AuditableObjectRole.Job }); SendAudit(audit); }
public UploadService( GraphQLRequest graphQlRequest, GraphQLClient graphQlClient, ApiSecret apiSecret, IIdentityProviderService service, IMemoryCache cache, ILogger <UploadService> logger) { _map = new Dictionary <string, Guid> { { "SDS_P1", new Guid("777CECC4-C140-477D-BD94-5A0A611F47FC") }, { "SDS_P2", new Guid("FB43A587-8251-4EA1-97B2-6F2F702952A6") }, { "humidity", new Guid("795F28B0-77ED-4A57-AF57-32A2C47CDBA0") }, { "temperature", new Guid("6E78294C-0AB6-4E71-A790-EA099D0693A6") }, { "BMP_pressure", new Guid("516C6AB3-E615-462E-8718-63FD85220D6A") }, { "BMP_temperature", new Guid("8FA026A5-BA9F-476A-AB7F-27406C3CEA91") }, }; _graphQlClient = graphQlClient; _graphQlRequest = graphQlRequest; _graphQlRequest.Query = Query.CreateMeasureValueBunch; //@"mutation AddValue($measure: MeasureValueInput!) { createMeasureValue(measureValueType: $measure){id}}"; //_graphQlRequest.OperationName = "AddValue"; _service = service; _apiSecret = apiSecret; _cache = cache; _logger = logger; _exp = DateTime.MinValue; }
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); }
public void TestGetNonAuthenticatedPrincipal() { IIdentityProviderService provider = ApplicationServiceContext.Current.GetService <IIdentityProviderService>(); var identity = provider.GetIdentity("*****@*****.**"); Assert.AreEqual("*****@*****.**", identity.Name); Assert.IsFalse(identity.IsAuthenticated); Assert.IsNull(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 TestAuthenticateFailure() { try { IIdentityProviderService provider = ApplicationServiceContext.Current.GetService <IIdentityProviderService>(); var principal = provider.Authenticate("*****@*****.**", "passwordz"); Assert.Fail("Should throw SecurityException"); } catch (AuthenticationException) { } }
public HttpUploadService( HttpClient client, ILogger <HttpUploadService> logger, IIdentityProviderService identity, ApiSecret secret) { _client = client; _client.Timeout = TimeSpan.FromSeconds(5); _logger = logger; _identity = identity; _secret = secret; }
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"); }
public void TestChangePassword() { var dataPersistence = ApplicationContext.Current.GetService <IDataPersistenceService <SecurityUser> >(); IIdentityProviderService identityProvider = ApplicationContext.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); 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 TestQueryValidResult() { IPasswordHashingService hashingService = ApplicationContext.Current.GetService <IPasswordHashingService>(); String securityHash = Guid.NewGuid().ToString(); SecurityUser userUnderTest = new SecurityUser() { Email = "*****@*****.**", EmailConfirmed = false, PasswordHash = hashingService.ComputeHash("password"), SecurityHash = securityHash, UserName = "******" }; var testUser = base.DoTestInsert(userUnderTest); IIdentityProviderService identityService = ApplicationContext.Current.GetService <IIdentityProviderService>(); var results = base.DoTestQuery(o => o.Email == "*****@*****.**", testUser.Key); Assert.AreEqual(1, results.Count()); Assert.AreEqual(userUnderTest.Email, results.First().Email); }
public void TestUpdateValidSecurityUser() { IPasswordHashingService hashingService = ApplicationContext.Current.GetService <IPasswordHashingService>(); SecurityUser userUnderTest = new SecurityUser() { Email = "*****@*****.**", EmailConfirmed = false, PasswordHash = hashingService.ComputeHash("password"), SecurityHash = "cert", UserName = "******" }; // Store user IIdentityProviderService identityService = ApplicationContext.Current.GetService <IIdentityProviderService>(); var userAfterUpdate = base.DoTestInsertUpdate(userUnderTest, "PhoneNumber"); // Update //Assert.IsNotNull(userAfterUpdate.UpdatedTime); Assert.IsNotNull(userAfterUpdate.PhoneNumber); }
/// <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)); } } }
public UserManagerService(IIdentityProviderService identityProviderService) { _identityProviderService = identityProviderService; }
public IdentityProviderController(IIdentityProviderService idpSvc) { _idpSvc = idpSvc; }
public SecurityService(IIdentityProviderService awsIdentityProviderService) { _identityProviderService = awsIdentityProviderService; }