private static List <HandlerTestScenario> GetClaimTestScenarios(
            object entity,
            SecurityClaimTypes[] claimsExpectedToSucceed)
        {
            return(GetEnumValues <SecurityClaimTypes>()
                   .Select(
                       claim =>
            {
                var user = ClaimsPrincipalUtils.CreateClaimsPrincipal(
                    Guid.NewGuid(),
                    new Claim(claim.ToString(), "")
                    );

                return new HandlerTestScenario
                {
                    User = user,
                    Entity = entity,
                    ExpectedToPass = claimsExpectedToSucceed.Contains(claim),
                    UnexpectedFailMessage =
                        "Expected claim " + claim + " to have caused the handler to succeed",
                    UnexpectedPassMessage = "Expected claim " + claim + " to have caused the handler to fail"
                };
            }
                       )
                   .ToList());
        }
        public async Task HasPreReleaseRoleWithinAccessWindowAuthorizationHandler_PreReleaseWindowNotOpen()
        {
            var release = new Release
            {
                Id = Guid.NewGuid()
            };

            var preReleaseService = new Mock <IPreReleaseService>();

            var userId = Guid.NewGuid();

            var failureScenario = new ReleaseHandlerTestScenario
            {
                Entity           = release,
                User             = ClaimsPrincipalUtils.CreateClaimsPrincipal(userId),
                UserReleaseRoles = new List <UserReleaseRole>
                {
                    new UserReleaseRole
                    {
                        ReleaseId = release.Id,
                        UserId    = userId,
                        Role      = PrereleaseViewer
                    }
                },
                ExpectedToPass        = false,
                UnexpectedPassMessage = "Expected the test to fail because the Pre Release window is not open at the " +
                                        "current time"
            };

            await GetEnumValues <PreReleaseAccess>()
            .Where(value => value != PreReleaseAccess.Within)
            .ToList()
            .ToAsyncEnumerable()
            .ForEachAwaitAsync(async access =>
            {
                preReleaseService
                .Setup(s => s.GetPreReleaseWindowStatus(release, It.IsAny <DateTime>()))
                .Returns(new PreReleaseWindowStatus
                {
                    Access = access
                });

                // Assert that a User who specifically has the Pre Release role will cause this handler to fail
                // IF the Pre Release window is NOT open
                await AssertReleaseHandlerHandlesScenarioSuccessfully <ViewReleaseRequirement>(
                    contentDbContext =>
                    new HasPreReleaseRoleWithinAccessWindowAuthorizationHandler(
                        new UserReleaseRoleRepository(contentDbContext),
                        preReleaseService.Object),
                    failureScenario);
            });
        }
Exemplo n.º 3
0
        /// <summary>
        /// Updates identity set on controller context
        /// </summary>
        /// <param name="Shooter">Shooter instance</param>
        protected void UpdateIdentityUser(Shooter Shooter)
        {
            //Validazione argomenti
            if (Shooter == null)
            {
                throw new ArgumentNullException(nameof(Shooter));
            }

            //impostazione local dell'identità
            CurrentIdentityUser = Shooter;

            //Generazione del principal
            var identity = ClaimsPrincipalUtils.GeneratesClaimsPrincipal("Mock", CurrentIdentityUser);

            Controller.ControllerContext = new ControllerContext
            {
                //HTTP context default
                HttpContext = new DefaultHttpContext
                {
                    //Imposto l'identity generata
                    User = identity
                }
            };
        }
Exemplo n.º 4
0
        /// <summary>
        /// Handle process for current authentication
        /// </summary>
        /// <returns></returns>
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            //Se non ho headers o non ho "Authentication", esco
            if (string.IsNullOrEmpty(Request.Headers?["Authorization"]))
            {
                //Fallisco l'autenticazione
                return(AuthenticateResult.Fail("Header 'Authorization' was not provided"));
                //return AuthenticateResult.NoResult();
            }

            //Recupero il valore e split
            string authValue = Request.Headers["Authorization"];
            var    segments  = authValue.Split(" ", StringSplitOptions.RemoveEmptyEntries);

            //Se non ho due elementi, esco
            if (segments.Length != 2)
            {
                //Fallisco l'autenticazione
                return(AuthenticateResult.Fail("Header 'Authorization' should contains two items: schema and value"));
                //return AuthenticateResult.NoResult();
            }

            //Se il lo schema non è Basic, esco
            if (segments[0] != "Basic" || string.IsNullOrEmpty(segments[1]))
            {
                //Fallisco l'autenticazione
                return(AuthenticateResult.Fail($"Provided schema is not '{Scheme.Name}'"));
                //return AuthenticateResult.NoResult();
            }

            string credentials;

            try
            {
                //Il valore dell'intestazione va decodificato dalla sua forma Base64
                //Per i dettagli, vedere: http://www.w3.org/Protocols/HTTP/1.0/spec.html#BasicAA
                credentials = Encoding.UTF8.GetString(Convert.FromBase64String(segments[1]));
            }
            catch
            {
                //Probabilmente la stringa base64 non era valida
                credentials = string.Empty;
            }

            //Username e password sono separati dal carattere delimitatore ":"
            //Terminiamo l'esecuzione se non è presente o se è in posizione non valida
            var indexOfSeparator = credentials.IndexOf(":", StringComparison.Ordinal);

            if (indexOfSeparator < 1 || indexOfSeparator > credentials.Length - 2)
            {
                //Fallisco l'autenticazione
                return(AuthenticateResult.Fail("Base64 encoded values should be separated by char ':'"));
            }

            //Estraiamo finalmente le credenziali
            var username = credentials.Substring(0, indexOfSeparator);
            var password = credentials.Substring(indexOfSeparator + 1);

            //Se username o password sono vuoti, esco
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                //Fallisco l'autenticazione
                return(AuthenticateResult.Fail("Username and/or password should not be empty or null"));
            }

            //Transazione isolata per il database con il solo scopo di identificare
            //l'accesso di emergenza, subito chiusa al termine dell'operazione
            using IDataSession isolatedSession = SessionFactory.OpenSession();

            //Service layer base
            using var serviceLayer = new AuthenticationServiceLayer(isolatedSession);

            //Tento di eseguire il sign-in dell'utente
            var signedInUser = await serviceLayer.SignIn(username, password);

            //Se non ho l'utente, esco
            if (signedInUser == null)
            {
                //Fallisco
                return(AuthenticateResult.Fail("Provided credentials are invalid"));
            }

            //Eseguo la generazione del principal
            var principal = ClaimsPrincipalUtils.GeneratesClaimsPrincipal(
                BasicAuthenticationOptions.Scheme, signedInUser);
            //Creo il ticket di autenticazione
            var authTicket = new AuthenticationTicket(principal, new AuthenticationProperties(), Scheme.Name);

            //Imposto il principal sul thread corrente
            Thread.CurrentPrincipal = principal;
            //Confermo l'autenticazione
            return(AuthenticateResult.Success(authTicket));
        }