Example #1
0
        private async Task <AuthResult> ValidateUserIdentity(string username, string password)
        {
            bool allowedAccess = await _ldapRepo.UserAllowedAccess(username);

            if (!allowedAccess)
            {
                return(AuthResult.Failed("User access not permitted."));
            }

            using (var conn = new LdapConnection())
            {
                try{
                    conn.Connect(_ldapSettings.Connection, _ldapSettings.Port);
                    conn.Bind(AddDomain(username), password);
                    return(AuthResult.Authenticated());
                }
                catch (LdapException ex)
                {
                    if (ex.ResultCode == 49)
                    {
                        return(AuthResult.Failed("Credentials failed authentication"));
                    }

                    _logger.LogError(LogEvents.UnexpectedAuthError, ex, "Unexpected LDAP exception.");
                    return(AuthResult.Failed("Credentials failed authentication"));
                }
                catch (Exception ex)
                {
                    _logger.LogError(LogEvents.UnexpectedAuthError, ex, "Unexpected LDAP exception.");
                    return(AuthResult.Failed("Credentials failed authentication"));
                }
            }
        }
        public async Task ProviderResultsReturned_ForValidCredentials()
        {
            // Arrange:
            var resourceModel   = new AuthResourceModel {
            };
            var credentialModel = new AuthCredentialModel {
                Api = "service-api", Credentials = new Dictionary <string, string> {
                }
            };
            var command = new AuthenticateCaller(credentialModel, resourceModel);

            // Create mock token service to return know token value
            var tokenSrv = new MockTokenService {
                ExpectedTokenValue = Guid.NewGuid().ToString()
            };

            // Assume provider also indicates valid submitted authentication request.
            var port = CreatePort(p => {
                p.IsValidRequest = true;
                p.HavingResult   = c => AuthResult.Authenticated();
            }, tokenSrv);

            // Act:
            var result = await port.AuthenticateForService(command);

            // Assert:
            Assert.NotNull(result);
            Assert.False(result.IsInvalidCredentialContext);
            Assert.True(result.IsAuthenticated);
            Assert.Equal(tokenSrv.ExpectedTokenValue, result.JwtSignedToken);
        }
Example #3
0
        private async Task <AuthResult> GetResourceAccessClaimAsync(AuthContext context, string userName)
        {
            ResourcePermission[] grantedAccessToResources = await _ldapRepo.GetUserAccessAsync(userName, context.Resources);

            var accessClaim = new Claim("access", grantedAccessToResources.ToJson());

            return(AuthResult.Authenticated(grantedAccessToResources, accessClaim));
        }
Example #4
0
        private async Task <AuthResult> GetResourceAccessClaimAsync(AuthContext context, Guid deviceId)
        {
            ResourcePermission[] grantedAccessToResources = await _deviceAuthRepo.GetDeviceAccessAsync(deviceId, context.Resources);

            Claim accessClaim = new Claim("access", grantedAccessToResources.ToJson());

            return(AuthResult.Authenticated(grantedAccessToResources, accessClaim));
        }
Example #5
0
        public async Task ResourcesToAuthenticateAccess_Received()
        {
            // Arrange:
            var mockMessaging = MockMessagingService.Setup(results => {
                var expectedResult = AuthResult.Authenticated().SetSignedToken("MOCK_TOKEN");
                results.RegisterResponse <AuthenticateCaller, AuthResult>(expectedResult);
            });

            var expectedService = "resource-owner";
            var scope1          = "repository:test/my-app:pull,push";
            var scope2          = "repository:test/my-app2:pull";

            var url = $@"api/boondocks/authentication?service={expectedService}&scope={scope1}&scope={scope2}";

            var plugin     = new MockAppHostPlugin();
            var httpClient = TestHttpClient.Create(plugin, mockMessaging);

            // Act:
            var credentials = new AuthCredentialModel {
            };
            var result      = await httpClient.AuthenticateAsync(url, credentials);

            // Assert:
            Assert.True(mockMessaging.ReceivedMessages.Count() == 1);

            var receivedCommand = (AuthenticateCaller)mockMessaging.ReceivedMessages.First();

            Assert.NotNull(receivedCommand.Context);

            // Assert Owning Service Submitted:
            Assert.Equal(receivedCommand.Context.ResourceOwner, expectedService);

            // Assert Resources to Authenticate Access:
            Assert.NotNull(receivedCommand.Context.Resources);
            Assert.True(receivedCommand.Context.Resources.Length == 2);

            // Assert First Resource Scope:
            var firstScope = receivedCommand.Context.Resources[0];

            Assert.Equal("repository", firstScope.Type);
            Assert.Equal("test/my-app", firstScope.Name);
            Assert.True(firstScope.Actions.Length == 2);
            Assert.Equal("pull", firstScope.Actions[0]);
            Assert.Equal("push", firstScope.Actions[1]);


            // Assert Second Resource Scope:
            var secondScope = receivedCommand.Context.Resources[1];

            Assert.Equal("repository", secondScope.Type);
            Assert.Equal("test/my-app2", secondScope.Name);
            Assert.True(secondScope.Actions.Length == 1);
            Assert.Equal("pull", firstScope.Actions[0]);
        }
Example #6
0
        public override async Task <AuthResult> OnAuthenticateAsync(AuthContext context)
        {
            string deviceToken = context.Credentials[DeviceTokenPropertyName];

            var validation = await _deviceAuthSrv.ValidateDeviceToken(deviceToken, ValidationParameters);

            if (validation.authResult.IsAuthenticated)
            {
                return(await GetResourceAccessClaimAsync(context, validation.deviceId));
            }

            if (validation.authResult.IsAuthenticated)
            {
                return(AuthResult.Authenticated());
            }

            return(AuthResult.Failed(validation.authResult.Reason));
        }
Example #7
0
        public async Task ClientCredentialsReceived_WhenSent()
        {
            // Arrange:
            var mockMessaging = MockMessagingService.Setup(results => {
                var expectedResult = AuthResult.Authenticated().SetSignedToken("MOCK_TOKEN");
                results.RegisterResponse <AuthenticateCaller, AuthResult>(expectedResult);
            });

            var plugin     = new MockAppHostPlugin();
            var httpClient = TestHttpClient.Create(plugin, mockMessaging);

            // Act:
            var credentialModle = new AuthCredentialModel
            {
                Credentials = new Dictionary <string, string>
                {
                    { "CertKey1", "CertValue1" },
                    { "CertKey2", "CertValue2" }
                }
            };

            var result = await httpClient.AuthenticateAsync(credentialModle);

            // Assert:
            Assert.True(mockMessaging.ReceivedMessages.Count() == 1);

            var receivedCommand = (AuthenticateCaller)mockMessaging.ReceivedMessages.First();

            Assert.NotNull(receivedCommand.Context);

            var receivedCredentials = receivedCommand.Context.Credentials;

            Assert.NotNull(receivedCredentials);

            Assert.True(receivedCredentials.ContainsKey("CertKey1"));
            Assert.True(receivedCredentials.ContainsKey("CertKey2"));
            Assert.Equal("CertValue1", receivedCredentials["CertKey1"]);
            Assert.Equal("CertValue2", receivedCredentials["CertKey2"]);
        }
Example #8
0
        public async Task ValidCredentials_ResourceAccess_Returned()
        {
            // Arrange:
            var allowedResourceAccess = new ResourcePermission[] {
                new ResourcePermission(type: "ResourceType", name: "ResourceName", actions: new string[] { "action1", "action2" })
            };

            var mockMessaging = MockMessagingService.Setup(results => {
                var expectedResult = AuthResult.Authenticated(allowedResourceAccess)
                                     .SetSignedToken("MOCK_TOKEN");
                results.RegisterResponse <AuthenticateCaller, AuthResult>(expectedResult);
            });

            var plugin     = new MockAppHostPlugin();
            var httpClient = TestHttpClient.Create(plugin, mockMessaging);

            // Act:
            var credentials = new AuthCredentialModel {
            };
            var result      = await httpClient.AuthenticateAsync(credentials);

            // Assert:
            var responseValue = await result.Content.ReadAsStringAsync();

            var resource = JsonConvert.DeserializeObject <AuthResultResource>(responseValue);
            var resourcesGrantedAccess = resource.GetEmbeddedCollection <AuthAccessResource>("resource-access");

            Assert.NotNull(resourcesGrantedAccess);
            Assert.True(resourcesGrantedAccess.Count() == 1);

            var access = resourcesGrantedAccess.First();

            Assert.Equal("ResourceType", access.Type);
            Assert.Equal("ResourceName", access.Name);
            Assert.True(access.Actions.Length == 2);
            Assert.Equal("action1", access.Actions[0]);
            Assert.Equal("action2", access.Actions[1]);
        }
Example #9
0
        public async Task ValidCredentials_OkStatus_WithTokenHeader()
        {
            // Arrange:
            var mockMessaging = MockMessagingService.Setup(results => {
                var expectedResult = AuthResult.Authenticated()
                                     .SetSignedToken("MOCK_TOKEN");
                results.RegisterResponse <AuthenticateCaller, AuthResult>(expectedResult);
            });

            var plugin     = new MockAppHostPlugin();
            var httpClient = TestHttpClient.Create(plugin, mockMessaging);

            // Act:
            var credentials = new AuthCredentialModel {
            };
            var result      = await httpClient.AuthenticateAsync(credentials);

            // Assert:
            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
            result.Headers.TryGetValues("X-Custom-Token", out IEnumerable <string> values);
            Assert.True(values.Count() == 1);
            Assert.Equal("MOCK_TOKEN", values.First());
        }