public void Query_GetAndSet()
        {
            var request = new DefaultHttpContext().Request;
            var requestFeature = request.HttpContext.Features.Get<IHttpRequestFeature>();
            Assert.Equal(string.Empty, requestFeature.QueryString);
            Assert.Equal(QueryString.Empty, request.QueryString);
            var query0 = request.Query;
            Assert.NotNull(query0);
            Assert.Equal(0, query0.Count);

            requestFeature.QueryString = "?name0=value0&name1=value1";
            var query1 = request.Query;
            Assert.NotSame(query0, query1);
            Assert.Equal(2, query1.Count);
            Assert.Equal("value0", query1["name0"]);
            Assert.Equal("value1", query1["name1"]);

            var query2 = new QueryCollection( new Dictionary<string, StringValues>()
            {
                { "name2", "value2" }
            });

            request.Query = query2;
            Assert.Same(query2, request.Query);
            Assert.Equal("?name2=value2", requestFeature.QueryString);
            Assert.Equal(new QueryString("?name2=value2"), request.QueryString);
        }
 protected override IEnumerableValueProvider GetEnumerableValueProvider(
     BindingSource bindingSource,
     Dictionary<string, StringValues> values,
     CultureInfo culture)
 {
     var backingStore = new QueryCollection(values);
     return new QueryStringValueProvider(bindingSource, backingStore, culture);
 }
示例#3
0
        public async Task AuthorizedConnectionCanConnectToEndPoint()
        {
            var manager    = CreateConnectionManager();
            var connection = manager.CreateConnection();
            var dispatcher = new HttpConnectionDispatcher(manager, new LoggerFactory());
            var context    = new DefaultHttpContext();

            context.Features.Set <IHttpResponseFeature>(new ResponseFeature());
            var services = new ServiceCollection();

            services.AddOptions();
            services.AddEndPoint <TestEndPoint>();
            services.AddAuthorizationPolicyEvaluator();
            services.AddAuthorization(o =>
            {
                o.AddPolicy("test", policy =>
                {
                    policy.RequireClaim(ClaimTypes.NameIdentifier);
                });
            });
            services.AddLogging();
            services.AddAuthenticationCore(o =>
            {
                o.DefaultScheme = "Default";
                o.AddScheme("Default", a => a.HandlerType = typeof(TestAuthenticationHandler));
            });
            var sp = services.BuildServiceProvider();

            context.Request.Path    = "/foo";
            context.Request.Method  = "GET";
            context.RequestServices = sp;
            var values = new Dictionary <string, StringValues>();

            values["id"] = connection.ConnectionId;
            var qs = new QueryCollection(values);

            context.Request.Query = qs;
            context.Response.Body = new MemoryStream();

            var builder = new SocketBuilder(sp);

            builder.UseEndPoint <TestEndPoint>();
            var app     = builder.Build();
            var options = new HttpSocketOptions();

            options.AuthorizationData.Add(new AuthorizeAttribute("test"));

            // "authorize" user
            context.User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "name") }));

            var endPointTask = dispatcher.ExecuteAsync(context, options, app);
            await connection.Transport.Out.WriteAsync(Encoding.UTF8.GetBytes("Hello, World")).OrTimeout();

            await endPointTask.OrTimeout();

            Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
            Assert.Equal("Hello, World", GetContentAsString(context.Response.Body));
        }
示例#4
0
        public async Task SelectSpecificationForFunding_GivenValidSpecification_ReturnsNoContentResult()
        {
            // Arrange
            IQueryCollection queryStringValues = new QueryCollection(new Dictionary <string, StringValues>
            {
                { "specificationId", new StringValues(SpecificationId) }
            });

            HttpRequest request = Substitute.For <HttpRequest>();

            request
            .Query
            .Returns(queryStringValues);

            Specification specification = CreateSpecification();

            ILogger logger = CreateLogger();

            ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository();

            specificationsRepository
            .GetSpecificationById(Arg.Is(SpecificationId))
            .Returns(specification);

            specificationsRepository
            .UpdateSpecification(Arg.Is(specification))
            .Returns(HttpStatusCode.OK);

            IJobsApiClient jobsApiClient = CreateJobsApiClient();

            ICacheProvider cacheProvider = CreateCacheProvider();

            SpecificationsService service = CreateService(
                logs: logger,
                specificationsRepository: specificationsRepository,
                jobsApiClient: jobsApiClient,
                cacheProvider: cacheProvider);

            // Act
            IActionResult result = await service.SelectSpecificationForFunding(request);

            // Assert
            result
            .Should()
            .BeOfType <NoContentResult>();

            await jobsApiClient
            .Received(1)
            .CreateJob(Arg.Is <JobCreateModel>(j => j.JobDefinitionId == JobConstants.DefinitionNames.PublishProviderResultsJob && j.SpecificationId == SpecificationId && j.Trigger.Message == $"Selecting specification for funding"));

            await cacheProvider
            .Received(1)
            .RemoveAsync <SpecificationSummary>($"{CacheKeys.SpecificationSummaryById}{specification.Id}");

            await cacheProvider
            .Received(1)
            .RemoveAsync <SpecificationCurrentVersion>($"{CacheKeys.SpecificationCurrentVersionById}{specification.Id}");
        }
示例#5
0
        public async Task EditSpecification_GivenSpecificationWasfoundAndFundingPeriodChangedButFailedToGetFundingPeriodsFromCosmos_ReturnsPreConditionFailedresult()
        {
            //Arrange
            SpecificationEditModel specificationEditModel = new SpecificationEditModel
            {
                FundingPeriodId = "fp10"
            };

            string json = JsonConvert.SerializeObject(specificationEditModel);

            byte[]       byteArray = Encoding.UTF8.GetBytes(json);
            MemoryStream stream    = new MemoryStream(byteArray);

            HttpContext context = Substitute.For <HttpContext>();

            HttpRequest request = Substitute.For <HttpRequest>();

            IQueryCollection queryStringValues = new QueryCollection(new Dictionary <string, StringValues>
            {
                { "specificationId", new StringValues(SpecificationId) },
            });

            request
            .Query
            .Returns(queryStringValues);
            request
            .Body
            .Returns(stream);

            request
            .HttpContext
            .Returns(context);

            ILogger logger = CreateLogger();

            Specification specification = CreateSpecification();

            ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository();

            specificationsRepository
            .GetSpecificationById(Arg.Is(SpecificationId))
            .Returns(specification);

            SpecificationsService service = CreateService(logs: logger, specificationsRepository: specificationsRepository);

            //Act
            IActionResult result = await service.EditSpecification(request);

            //Arrange
            result
            .Should()
            .BeOfType <PreconditionFailedResult>()
            .Which
            .Value
            .Should()
            .Be($"Unable to find funding period with ID '{specificationEditModel.FundingPeriodId}'.");
        }
示例#6
0
        public async Task EditSpecification_WhenInvalidModelProvided_ThenValidationErrorReturned()
        {
            // Arrange
            ValidationResult validationResult = new ValidationResult();

            validationResult.Errors.Add(new ValidationFailure("error", "error"));

            IValidator <SpecificationEditModel> validator = CreateEditSpecificationValidator(validationResult);

            SpecificationsService specificationsService = CreateService(specificationEditModelValidator: validator);

            SpecificationEditModel specificationEditModel = new SpecificationEditModel();

            string json = JsonConvert.SerializeObject(specificationEditModel);

            byte[]       byteArray = Encoding.UTF8.GetBytes(json);
            MemoryStream stream    = new MemoryStream(byteArray);

            HttpContext context = Substitute.For <HttpContext>();

            HttpRequest request = Substitute.For <HttpRequest>();

            IQueryCollection queryStringValues = new QueryCollection(new Dictionary <string, StringValues>
            {
                { "specificationId", new StringValues(SpecificationId) },
            });

            request
            .Query
            .Returns(queryStringValues);
            request
            .Body
            .Returns(stream);

            request
            .HttpContext
            .Returns(context);

            // Act
            IActionResult result = await specificationsService.EditSpecification(request);

            // Assert
            result
            .Should()
            .BeOfType <BadRequestObjectResult>()
            .Which
            .Value
            .Should()
            .BeOfType <SerializableError>()
            .Which
            .Should()
            .HaveCount(1);

            await validator
            .Received(1)
            .ValidateAsync(Arg.Any <SpecificationEditModel>());
        }
    protected override IEnumerableValueProvider GetEnumerableValueProvider(
        BindingSource bindingSource,
        Dictionary <string, StringValues> values,
        CultureInfo culture)
    {
        var backingStore = new QueryCollection(values);

        return(new QueryStringValueProvider(bindingSource, backingStore, culture));
    }
示例#8
0
        public async Task MessageHandlerMiddlewareInvokeTest()
        {
            var ecryptXml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<xml>
    <ToUserName><![CDATA[gh_a96a4a619366]]></ToUserName>
    <Encrypt><![CDATA[wVQjGs46yqw0j5IhISmROAFui9lgiZB3VM1rYd73dYMzYJSvRbYQe0f+K+mo/4iGgrqnQA0FucnRBj/FNY7PIku/s4FZ+jC5kK/LXCgsdN/57w9qcatKvvRLDaPrLiUZ+AFBkFjSqkRUZWAgVbBk8tpwtt8R22m0BoNqLcV1n2gRjX05b/Lw+fEm//7tX+yu2f66PNN2GiRFGKbvMasVHXKdqIRqW4224C3p0G7YxPEHLSTH1AWMjl9mDvIbtgCIMQ/yZf+Cm27B+pscDD9ocPl5ruc92yRGTtcjYmd0bQxW1eBAJJiIpA9TzZKjIxwIyoJ3jK56GUu25iC6KuBIQi357JhygGLSaoC6TlWMlJFEIxtd2JKHVEzGNJ+LuQrU5jgnMLLhSxsq5u8r/VMbyKroXGpWNvu9irPrcMhC4L0=]]></Encrypt>
</xml>
";
            //var postModel = new PostModel()
            //{
            //    Signature = "330ed3b64e363dc876f35e54a79e59b48739f567",
            //    Msg_Signature = "20f4a1263d198b696e6958e0d65e928aa68f7d96",
            //    Timestamp = "1570032739",
            //    Nonce = "2068872452",

            //    Token = "weixin",
            //    EncodingAESKey = "mNnY5GekpChwqhy2c4NBH90g3hND6GeI4gii2YCvKLY",
            //    AppId = "wx669ef95216eef885"
            //};



            var contextMock = new Moq.Mock <HttpContext>();

            contextMock.Setup(z => z.Request.Query).Returns(() =>
            {
                var dic              = new Dictionary <string, StringValues>();
                dic["nonce"]         = "863153744";
                dic["timestamp"]     = "1570075722";
                dic["msg_signature"] = "71dc359205a4660bc3b3046b643452c994b5897d";
                dic["signature"]     = "330ed3b64e363dc876f35e54a79e59b48739f567";

                var query = new QueryCollection(dic);
                return(query);
            });

            //TODO:此处并没有完全模拟成功 Post,致使 context.Request.GetRequestMemoryStream() 无法正确获取到数据

            var requestStream = GetStream(ecryptXml);

            contextMock.Setup(z => z.Request.Body).Returns(requestStream);
            contextMock.Setup(z => z.Request.Method).Returns("POST");
            contextMock.Setup(z => z.Features).Returns(new FeatureCollection());

            var messageHandlerMiddleware = new MpMessageHandlerMiddleware <DefaultMpMessageContext>(null, CustomMessageHandlers.GenerateMessageHandler, options =>
            {
                options.DefaultMessageHandlerAsyncEvent = NeuChar.MessageHandlers.DefaultMessageHandlerAsyncEvent.SelfSynicMethod;
                options.AccountSettingFunc = context => new SenparcWeixinSetting()
                {
                    Token          = "weixin",
                    EncodingAESKey = "YTJkZmVjMzQ5NDU5NDY3MDhiZWI0NTdiMjFiY2I5MmU",
                    WeixinAppId    = "wx669ef95216eef885"
                };
            });

            await messageHandlerMiddleware.Invoke(contextMock.Object);
        }
示例#9
0
        public static HttpRequest FakeRequestWithQuery(Dictionary <string, string> queryParams)
        {
            var dict            = queryParams.ToDictionary(q => q.Key, q => new StringValues(q.Value));
            var queryCollection = new QueryCollection(dict);
            var request         = new DefaultHttpContext().Request;

            request.Query = queryCollection;
            return(request);
        }
        public async Task EditCalculationStatus_GivenCurrentCalculationWasNotFound_ReturnsNotFoundResult()
        {
            //Arrange
            EditStatusModel CalculationEditStatusModel = new EditStatusModel
            {
                PublishStatus = PublishStatus.Approved
            };

            string json = JsonConvert.SerializeObject(CalculationEditStatusModel);

            byte[]       byteArray = Encoding.UTF8.GetBytes(json);
            MemoryStream stream    = new MemoryStream(byteArray);

            HttpContext context = Substitute.For <HttpContext>();

            HttpRequest request = Substitute.For <HttpRequest>();

            IQueryCollection queryStringValues = new QueryCollection(new Dictionary <string, StringValues>
            {
                { "calculationId", new StringValues(CalculationId) },
            });

            request
            .Query
            .Returns(queryStringValues);
            request
            .Body
            .Returns(stream);

            request
            .HttpContext
            .Returns(context);

            ILogger logger = CreateLogger();

            Calculation calculation = new Calculation();

            ICalculationsRepository CalculationsRepository = CreateCalculationsRepository();

            CalculationsRepository
            .GetCalculationById(Arg.Is(CalculationId))
            .Returns(calculation);

            CalculationService service = CreateCalculationService(logger: logger, calculationsRepository: CalculationsRepository);

            //Act
            IActionResult result = await service.UpdateCalculationStatus(request);

            //Arrange
            result
            .Should()
            .BeOfType <NotFoundResult>();

            logger
            .Received(1)
            .Warning(Arg.Is($"A current calculation was not found for calculation id {CalculationId}"));
        }
示例#11
0
        async public Task GetCalculationSummariesForSpecification_WhenCalculationsNotFoundInCacheAndResponseFromRepositoryIsNull_ThenErrorReturned()
        {
            // Arrange
            const string specificationId = "specid";

            IQueryCollection queryStringValues = new QueryCollection(new Dictionary <string, StringValues>
            {
                { "specificationId", new StringValues(specificationId) }
            });

            HttpRequest request = Substitute.For <HttpRequest>();

            request
            .Query
            .Returns(queryStringValues);

            ILogger logger = CreateLogger();

            ICalculationsRepository calculationsRepository = CreateCalculationsRepository();

            calculationsRepository
            .GetCalculationsBySpecificationId(Arg.Is(specificationId))
            .Returns((IEnumerable <Calculation>)null);

            ICacheProvider cacheProvider = CreateCacheProvider();

            cacheProvider
            .GetAsync <List <CalculationSummaryModel> >($"{CacheKeys.CalculationsSummariesForSpecification}{specificationId}")
            .Returns((List <CalculationSummaryModel>)null);

            CalculationService service = CreateCalculationService(logger: logger, calculationsRepository: calculationsRepository, cacheProvider: cacheProvider);

            // Act
            IActionResult result = await service.GetCalculationSummariesForSpecification(request);

            // Assert
            result
            .Should()
            .BeOfType <InternalServerErrorResult>()
            .Which
            .Value
            .Should()
            .Be("Calculations from repository returned null");

            await calculationsRepository
            .Received(1)
            .GetCalculationsBySpecificationId(Arg.Is(specificationId));

            await cacheProvider
            .Received(1)
            .GetAsync <List <CalculationSummaryModel> >($"{CacheKeys.CalculationsSummariesForSpecification}{specificationId}");

            logger
            .Received(1)
            .Warning($"Calculations from repository returned null for specification ID of '{specificationId}'");
        }
示例#12
0
        public async Task EditPolicy_WhenValidModelButPolicyCouldNotBeFound_ThenReturnsNotFoundResult()
        {
            // Arrange
            PolicyEditModel policyEditModel = new PolicyEditModel
            {
                SpecificationId = SpecificationId
            };

            string json = JsonConvert.SerializeObject(policyEditModel);

            byte[]       byteArray = Encoding.UTF8.GetBytes(json);
            MemoryStream stream    = new MemoryStream(byteArray);

            HttpContext context = Substitute.For <HttpContext>();

            HttpRequest request = Substitute.For <HttpRequest>();

            IQueryCollection queryStringValues = new QueryCollection(new Dictionary <string, StringValues>
            {
                { "specificationId", new StringValues(SpecificationId) },
                { "policyId", new StringValues(PolicyId) },
            });

            request
            .Query
            .Returns(queryStringValues);
            request
            .Body
            .Returns(stream);

            request
            .HttpContext
            .Returns(context);

            Specification specification = CreateSpecification();

            ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository();

            specificationsRepository
            .GetSpecificationById(Arg.Is(SpecificationId))
            .Returns(specification);

            SpecificationsService specificationsService = CreateService(specificationsRepository: specificationsRepository);

            // Act
            IActionResult result = await specificationsService.EditPolicy(request);

            // Assert
            result
            .Should()
            .BeOfType <NotFoundObjectResult>()
            .Which
            .Value
            .Should()
            .Be($"Failed to find policy for policy id: {PolicyId}");
        }
示例#13
0
        protected override Expression VisitBinary(BinaryExpression node)
        {
            if (QueryCollection.ContainsKey(Context))
            {
                Append(" and ");
            }

            Visit(node.Left);

            Append(" ");

            switch (node.NodeType)
            {
            case ExpressionType.Equal:
                Append("eq");
                break;

            case ExpressionType.NotEqual:
                Append("ne");
                break;

            case ExpressionType.GreaterThan:
                Append("gt");
                break;

            case ExpressionType.GreaterThanOrEqual:
                Append("ge");
                break;

            case ExpressionType.LessThan:
                Append("lt");
                break;

            case ExpressionType.LessThanOrEqual:
                Append("le");
                break;

            /*case ExpressionType.AndAlso:
             * case ExpressionType.And:
             *  Append("and");
             *  break;*/
            case ExpressionType.OrElse:
                Append("or");
                break;

            case ExpressionType.Not:
                Append("not");
                break;
            }

            Append(" ");

            Visit(node.Right);

            return(node);
        }
示例#14
0
        public async Task EditSpecification_GivenSpecificationWasNotFound_ReturnsNotFoundResult()
        {
            //Arrange
            SpecificationEditModel specificationEditModel = new SpecificationEditModel();

            string json = JsonConvert.SerializeObject(specificationEditModel);

            byte[]       byteArray = Encoding.UTF8.GetBytes(json);
            MemoryStream stream    = new MemoryStream(byteArray);

            HttpContext context = Substitute.For <HttpContext>();

            HttpRequest request = Substitute.For <HttpRequest>();

            IQueryCollection queryStringValues = new QueryCollection(new Dictionary <string, StringValues>
            {
                { "specificationId", new StringValues(SpecificationId) },
            });

            request
            .Query
            .Returns(queryStringValues);
            request
            .Body
            .Returns(stream);

            request
            .HttpContext
            .Returns(context);

            ILogger logger = CreateLogger();

            ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository();

            specificationsRepository
            .GetSpecificationById(Arg.Is(SpecificationId))
            .Returns((Specification)null);

            SpecificationsService service = CreateService(logs: logger, specificationsRepository: specificationsRepository);

            //Act
            IActionResult result = await service.EditSpecification(request);

            //Arrange
            result
            .Should()
            .BeOfType <NotFoundObjectResult>()
            .Which
            .Value
            .Should()
            .Be("Specification not found");

            logger
            .Received(1)
            .Warning(Arg.Is($"Failed to find specification for id: {SpecificationId}"));
        }
示例#15
0
        public Grid(IEnumerable <T> source)
        {
            Query      = new QueryCollection();
            Source     = source.AsQueryable();
            Attributes = new GridHtmlAttributes();
            Processors = new HashSet <IGridProcessor <T> >();

            Columns = new GridColumns <T>(this);
            Rows    = new GridRows <T>(this);
        }
示例#16
0
        public void ParseFromQuery_EmptyQuery_ReturnsNull()
        {
            var userAccountRecoveryUrlHelper = new AuthorizedTaskTokenUrlHelper();

            var queryCollection = new QueryCollection();

            var result = userAccountRecoveryUrlHelper.ParseTokenFromQuery(queryCollection);

            Assert.Null(result);
        }
        public void ShouldAuthPatientReadAsOwnerUsingParameter()
        {
            // Setup
            string hdid         = "The User HDID";
            string resourceHDID = hdid;
            string token        = "Fake Access Token";
            string userId       = "User ID";
            string username     = "******";

            List <Claim> claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, username),
                new Claim(ClaimTypes.NameIdentifier, userId),
                new Claim(GatewayClaims.HDID, hdid),
            };
            ClaimsIdentity  identity        = new ClaimsIdentity(claims, "TestAuth");
            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);


            IHeaderDictionary headerDictionary = new HeaderDictionary();

            headerDictionary.Add("Authorization", token);
            IQueryCollection query = new QueryCollection(new Dictionary <string, StringValues>()
            {
                { "hdid", resourceHDID }
            });
            Mock <HttpRequest> httpRequestMock = new Mock <HttpRequest>();

            httpRequestMock.Setup(s => s.Headers).Returns(headerDictionary);
            httpRequestMock.Setup(s => s.Query).Returns(query);

            Mock <HttpContext> httpContextMock = new Mock <HttpContext>();

            httpContextMock.Setup(s => s.User).Returns(claimsPrincipal);
            httpContextMock.Setup(s => s.Request).Returns(httpRequestMock.Object);

            Mock <IHttpContextAccessor> httpContextAccessorMock = new Mock <IHttpContextAccessor>();

            httpContextAccessorMock.Setup(s => s.HttpContext).Returns(httpContextMock.Object);

            using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
            ILogger <FhirResourceAuthorizationHandler> logger = loggerFactory.CreateLogger <FhirResourceAuthorizationHandler>();

            FhirResourceAuthorizationHandler authHandler = new FhirResourceAuthorizationHandler(
                logger,
                httpContextAccessorMock.Object
                );
            var requirements = new[] { new FhirRequirement(FhirResource.Patient, FhirAccessType.Read, fhirLookup: FhirResourceLookup.Parameter) };

            AuthorizationHandlerContext context = new AuthorizationHandlerContext(requirements, claimsPrincipal, null);

            authHandler.HandleAsync(context);
            Assert.True(context.HasSucceeded);
            Assert.False(context.HasFailed);
        }
示例#18
0
        //========================================================================================
        // ReportPlans()
        //========================================================================================

        public void ReportPlans(QueryCollection queries)
        {
            if (!tabset.Contains(planPage))
            {
                // always append to end of tab set
                tabset.TabPages.Add(planPage);
            }

            planView.ReportPlans(queries);
            planPage.Selected = true;
        }
        public async Task AuthorizedConnectionWithRejectedSchemesFailsToConnectToEndPoint()
        {
            var manager    = CreateConnectionManager();
            var connection = manager.CreateConnection();
            var dispatcher = new HttpConnectionDispatcher(manager, new LoggerFactory());
            var context    = new DefaultHttpContext();
            var services   = new ServiceCollection();

            services.AddOptions();
            services.AddEndPoint <TestEndPoint>();
            services.AddAuthorization(o =>
            {
                o.AddPolicy("test", policy =>
                {
                    policy.RequireClaim(ClaimTypes.NameIdentifier);
                    policy.AddAuthenticationSchemes("Default");
                });
            });
            services.AddAuthorizationPolicyEvaluator();
            services.AddLogging();
            services.AddAuthenticationCore(o =>
            {
                o.DefaultScheme = "Default";
                o.AddScheme("Default", a => a.HandlerType = typeof(RejectHandler));
            });
            var sp = services.BuildServiceProvider();

            context.Request.Path    = "/foo";
            context.Request.Method  = "GET";
            context.RequestServices = sp;
            var values = new Dictionary <string, StringValues>();

            values["id"] = connection.ConnectionId;
            var qs = new QueryCollection(values);

            context.Request.Query = qs;
            context.Response.Body = new MemoryStream();

            var builder = new SocketBuilder(sp);

            builder.UseEndPoint <TestEndPoint>();
            var app     = builder.Build();
            var options = new HttpSocketOptions();

            options.AuthorizationData.Add(new AuthorizeAttribute("test"));

            // "authorize" user
            context.User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "name") }));

            // would block if EndPoint was executed
            await dispatcher.ExecuteAsync(context, options, app).OrTimeout();

            Assert.Equal(StatusCodes.Status401Unauthorized, context.Response.StatusCode);
        }
示例#20
0
        public void ReturnEmptyKey_With_QueryStringList()
        {
            //Arrange
            var queryDict = new QueryCollection();

            //Act
            var sut = RedisHelper.QueryStringKeyGenerator(queryDict);

            //Assert
            sut.Should().BeEmpty();
        }
        public async Task GetSpecificationSummaryById_GivenSpecificationSummaryWasNotFound_ReturnsNotFoundResult()
        {
            //Arrange
            Specification specification = null;

            IQueryCollection queryStringValues = new QueryCollection(new Dictionary <string, StringValues>
            {
                { "specificationId", new StringValues(SpecificationId) }
            });

            HttpRequest request = Substitute.For <HttpRequest>();

            request
            .Query
            .Returns(queryStringValues);

            ILogger logger = CreateLogger();

            ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository();

            specificationsRepository
            .GetSpecificationById(Arg.Is(SpecificationId))
            .Returns(specification);

            IMapper mapper = CreateImplementedMapper();

            ICacheProvider cacheProvider = CreateCacheProvider();

            cacheProvider
            .GetAsync <SpecificationSummary>(Arg.Is($"{CacheKeys.SpecificationSummaryById}{SpecificationId}"))
            .Returns((SpecificationSummary)null);

            SpecificationsService service = CreateService(
                specificationsRepository: specificationsRepository,
                cacheProvider: cacheProvider,
                logs: logger,
                mapper: mapper);

            //Act
            IActionResult result = await service.GetSpecificationSummaryById(request);

            //Assert
            result
            .Should()
            .BeOfType <NotFoundResult>();

            await specificationsRepository
            .Received(1)
            .GetSpecificationById(Arg.Is(SpecificationId));

            await cacheProvider
            .Received(1)
            .GetAsync <SpecificationSummary>(Arg.Is($"{CacheKeys.SpecificationSummaryById}{SpecificationId}"));
        }
示例#22
0
        public static HttpRequestMessage CreateHttpRequestMessage(string queryStringKey, string queryStringValue)
        {
            var request = CreateRequestMessage();

            var query = new QueryCollection(CreateDictionary(queryStringKey, queryStringValue)).ToString();
            var uri   = new Uri(request.RequestUri.PathAndQuery + query);

            request.RequestUri = uri;

            return(request);
        }
示例#23
0
        protected CollectionBase  GenerateQueryCollectionFromReader(IDataReader returnData)
        {
            QueryCollection qCollection = new QueryCollection();

            while (returnData.Read())
            {
                Query newQuery = new Query((int)returnData["QueryId"], (string)returnData["QueryName"]);
                qCollection.Add(newQuery);
            }
            return(qCollection);
        }
示例#24
0
        public async Task GetSpecificationsSelectedForFundingByPeriod_GivenSpecificationWasNotFound_ReturnsNotFound()
        {
            //Arrange
            SpecificationVersion sv1 = new SpecificationVersion {
                SpecificationId = "spec1", FundingPeriod = new Reference {
                    Id = "18/19", Name = "18/19"
                }
            };
            SpecificationVersion sv2 = new SpecificationVersion {
                SpecificationId = "spec2", FundingPeriod = new Reference {
                    Id = "17/18", Name = "17/18"
                }
            };

            Specification spec1 = new Specification {
                Id = "spec1", IsSelectedForFunding = true, Current = sv1
            };
            Specification spec2 = new Specification {
                Id = "spec2", IsSelectedForFunding = true, Current = sv2
            };

            IQueryCollection queryStringValues = new QueryCollection(new Dictionary <string, StringValues>
            {
                { "fundingPeriodId", new StringValues(FundingPeriodId) }
            });

            HttpRequest request = Substitute.For <HttpRequest>();

            request
            .Query
            .Returns(queryStringValues);

            ILogger logger = CreateLogger();

            ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository();

            specificationsRepository
            .GetSpecificationsByQuery(Arg.Any <Expression <Func <Specification, bool> > >())
            .Returns((Enumerable.Empty <Specification>()));

            SpecificationsService service = CreateService(specificationsRepository: specificationsRepository, logs: logger);

            //Act
            IActionResult result = await service.GetSpecificationsSelectedForFundingByPeriod(request);

            //Assert
            result
            .Should()
            .BeOfType <NotFoundResult>();

            logger
            .Received(1)
            .Information(Arg.Is($"Specification was not found for funding period: {FundingPeriodId}"));
        }
示例#25
0
        private IQueryCollection GenerateResetPasswordQueryParams(string token, string username)
        {
            var queryParams = new QueryCollection(
                new Dictionary <string, StringValues>()
            {
                { "token", token },
                { "username", username }
            });

            return(queryParams);
        }
示例#26
0
        public void No_Query_Parameters_Provided()
        {
            // Arrange
            var queryString = new QueryCollection(new Dictionary <string, StringValues> {
            });

            // Act
            var result = _sut.Parse(queryString);

            // Assert
            Assert.Equal(0, result.Length);
        }
        public void UnknownSortException()
        {
            var queryColletion = new QueryCollection(
                new Dictionary <string, StringValues>(new[]
            {
                new KeyValuePair <string, StringValues>("Sort", new StringValues("a"))
            }
                                                      ));
            var pageableModelBinder = new PageableModelBinder <Customer>(new AutumnSettings());

            Assert.Throws <UnknownSortException>(() => pageableModelBinder.Build(queryColletion));
        }
示例#28
0
        private Mock <HttpRequest> SetupHttpRequest(ConcentratorCredentialType credentialType = ConcentratorCredentialType.Cups)
        {
            var httpRequest     = new Mock <HttpRequest>();
            var queryCollection = new QueryCollection(new Dictionary <string, StringValues>()
            {
                { "StationEui", new StringValues(this.stationEui.ToString()) },
                { "CredentialType", credentialType.ToString() }
            });

            httpRequest.SetupGet(x => x.Query).Returns(queryCollection);
            return(httpRequest);
        }
        public void OutOfRangePageSizeException()
        {
            var queryColletion = new QueryCollection(
                new Dictionary <string, StringValues>(new[]
            {
                new KeyValuePair <string, StringValues>("PageSize", new StringValues("-1"))
            }
                                                      ));
            var pageableModelBinder = new PageableModelBinder <object>(new AutumnSettings());

            Assert.Throws <OutOfRangePageSizeException>(() => pageableModelBinder.Build(queryColletion));
        }
        public void InvalidPageNumberValueException()
        {
            var queryColletion = new QueryCollection(
                new Dictionary <string, StringValues>(new[]
            {
                new KeyValuePair <string, StringValues>("PageNumber", new StringValues("a"))
            }
                                                      ));
            var pageableModelBinder = new PageableModelBinder <object>(new AutumnSettings());

            Assert.Throws <InvalidPageNumberValueException>(() => pageableModelBinder.Build(queryColletion));
        }
示例#31
0
        /// <summary>
        ///
        /// Execute Multiple queries and return result of each query in a list
        ///
        /// </summary>
        /// <param name="sql">sql splitted by '/'</param>
        /// <param name="lstParams">Parameters for each query </param>
        /// <returns>
        /// json dataset</returns>
        public JsonResult ExecuteNonQueryWithCode(SqlParamsIn sqlIn)
        {
            SqlHelper h   = new SqlHelper();
            Ctx       ctx = Session["ctx"] as Ctx;

            h.SetContext(ctx);
            //sqlIn.sql = SecureEngineBridge.DecryptByClientKey(sqlIn.sql, ctx.GetSecureKey());
            sqlIn.sql = QueryCollection.GetQuery(sqlIn.sql, ctx);
            object data = h.ExecuteNonQuery(sqlIn);

            return(Json(JsonConvert.SerializeObject(data), JsonRequestBehavior.AllowGet));
        }
示例#32
0
        public void DoNotDuplicateQueryWhenCallingGetQuery()
        {
            var collection = new QueryCollection();
            var user       = new User("Test");
            var query      = new Query(user);

            collection.Add(query);
            var query2 = collection.GetQuery(user);

            Assert.Single(collection);
            Assert.Same(query, query2);
        }
示例#33
0
        protected override void LoadDocument(string filename)
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.Load(filename);

            _queries = new QueryCollection(this);

            foreach (XmlNode node in xmlDocument.SelectNodes(@"xinq/queries/query"))
            {
                var query = new Query(this, node);
                _queries.Add(query);
            }
        }
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = new HttpResponseMessage();

            if (request.RequestUri.AbsoluteUri.StartsWith("https://graph.facebook.com/v2.5/oauth/access_token"))
            {
                var formData = new FormCollection(await FormReader.ReadFormAsync(await request.Content.ReadAsStreamAsync()));
                if (formData["grant_type"] == "authorization_code")
                {
                    if (formData["code"] == "ValidCode")
                    {
                        Helpers.ThrowIfConditionFailed(() => ((string)formData["redirect_uri"]).EndsWith("signin-facebook"), "Redirect URI is not ending with /signin-facebook");
                        Helpers.ThrowIfConditionFailed(() => formData["client_id"] == "[AppId]", "Invalid client Id received");
                        Helpers.ThrowIfConditionFailed(() => formData["client_secret"] == "[AppSecret]", "Invalid client secret received");
                        response.Content = new StringContent("{ \"access_token\": \"ValidAccessToken\", \"expires_in\": \"100\" }");
                        return response;
                    }
                    response.StatusCode = (HttpStatusCode)400;
                    return response;
                }
            }
            else if (request.RequestUri.AbsoluteUri.StartsWith("https://graph.facebook.com/v2.5/me"))
            {
                var queryParameters = new QueryCollection(QueryHelpers.ParseQuery(request.RequestUri.Query));
                Helpers.ThrowIfConditionFailed(() => queryParameters["appsecret_proof"].Count > 0, "appsecret_proof is empty");
                if (queryParameters["access_token"] == "ValidAccessToken")
                {
                    response.Content = new StringContent("{\"id\":\"Id\",\"name\":\"AspnetvnextTest AspnetvnextTest\",\"first_name\":\"AspnetvnextTest\",\"last_name\":\"AspnetvnextTest\",\"link\":\"https:\\/\\/www.facebook.com\\/myLink\",\"username\":\"AspnetvnextTest.AspnetvnextTest.7\",\"gender\":\"male\",\"email\":\"AspnetvnextTest\\u0040test.com\",\"timezone\":-7,\"locale\":\"en_US\",\"verified\":true,\"updated_time\":\"2013-08-06T20:38:48+0000\",\"CertValidatorInvoked\":\"ValidAccessToken\"}");
                }
                else
                {
                    response.Content = new StringContent("{\"error\":{\"message\":\"Invalid OAuth access token.\",\"type\":\"OAuthException\",\"code\":190}}");
                }
                return response;
            }

            throw new NotImplementedException(request.RequestUri.AbsoluteUri);
        }
        public async Task LoginWithMicrosoftAccount()
        {
            _httpClientHandler = new HttpClientHandler() { AllowAutoRedirect = false };
            _httpClient = new HttpClient(_httpClientHandler) { BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri) };

            var response = await DoGetAsync("Account/Login");
            await ThrowIfResponseStatusNotOk(response);
            var responseContent = await response.Content.ReadAsStringAsync();
            _logger.LogInformation("Signing in with Microsoft account");
            var formParameters = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("provider", "Microsoft"),
                new KeyValuePair<string, string>("returnUrl", "/"),
                new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLogin")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Account/ExternalLogin", content);
            Assert.StartsWith("https://login.microsoftonline.com/common/oauth2/v2.0/authorize", response.Headers.Location.ToString());
            var queryItems = new QueryCollection(QueryHelpers.ParseQuery(response.Headers.Location.Query));
            Assert.Equal<string>("code", queryItems["response_type"]);
            Assert.Equal<string>("[ClientId]", queryItems["client_id"]);
            Assert.Equal<string>(_deploymentResult.ApplicationBaseUri + "signin-microsoft", queryItems["redirect_uri"]);
            Assert.Equal<string>("https://graph.microsoft.com/user.read wl.basic wl.signin", queryItems["scope"]);
            Assert.Equal<string>("ValidStateData", queryItems["state"]);
            Assert.Equal<string>("custom", queryItems["custom_redirect_uri"]);

            //Check for the correlation cookie
            Assert.NotEmpty(
                _httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri))
                .Cast<Cookie>()
                .Where(cookie => cookie.Name.StartsWith(".AspNetCore.Correlation.Microsoft")));

            //This is just to generate a correlation cookie. Previous step would generate this cookie, but we have reset the handler now.
            _httpClientHandler = new HttpClientHandler();
            _httpClient = new HttpClient(_httpClientHandler) { BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri) };

            response = await DoGetAsync("Account/Login");
            responseContent = await response.Content.ReadAsStringAsync();
            formParameters = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("provider", "Microsoft"),
                new KeyValuePair<string, string>("returnUrl", "/"),
                new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLogin")),
            };

            content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Account/ExternalLogin", content);
            //Post a message to the MicrosoftAccount middleware
            response = await DoGetAsync("signin-microsoft?code=ValidCode&state=ValidStateData");
            await ThrowIfResponseStatusNotOk(response);
            responseContent = await response.Content.ReadAsStringAsync();

            //Correlation cookie not getting cleared after successful signin?
            if (!Helpers.RunningOnMono)
            {
                Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(".AspNetCore.Correlation.Microsoft"));
            }
            Assert.Equal(_deploymentResult.ApplicationBaseUri + "Account/ExternalLoginCallback?ReturnUrl=%2F", response.RequestMessage.RequestUri.AbsoluteUri);

            formParameters = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("Email", "*****@*****.**"),
                new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLoginConfirmation?ReturnUrl=%2F")),
            };

            content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Account/ExternalLoginConfirmation", content);
            await ThrowIfResponseStatusNotOk(response);
            responseContent = await response.Content.ReadAsStringAsync();

            Assert.Contains(string.Format("Hello {0}!", "*****@*****.**"), responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("Log off", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie sent
            Assert.NotNull(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(IdentityCookieName));
            Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(ExternalLoginCookieName));
            _logger.LogInformation("Successfully signed in with user '{email}'", "*****@*****.**");

            _logger.LogInformation("Verifying if the middleware events were fired");
            //Check for a non existing item
            response = await DoGetAsync(string.Format("Admin/StoreManager/GetAlbumIdFromName?albumName={0}", "123"));
            //This action requires admin permissions. If events are fired this permission is granted
            _logger.LogInformation(await response.Content.ReadAsStringAsync());
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            _logger.LogInformation("Middleware events were fired successfully");
        }
示例#36
0
 public XinqDocument()
 {
     _queries = new QueryCollection(this);
 }
        public async Task LoginWithTwitter()
        {
            _httpClientHandler = new HttpClientHandler() { AllowAutoRedirect = false };
            _httpClient = new HttpClient(_httpClientHandler) { BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri) };

            var response = await _httpClient.GetAsync("Account/Login");
            await ThrowIfResponseStatusNotOk(response);
            var responseContent = await response.Content.ReadAsStringAsync();
            _logger.LogInformation("Signing in with Twitter account");
            var formParameters = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("provider", "Twitter"),
                new KeyValuePair<string, string>("returnUrl", "/"),
                new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLogin")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await _httpClient.PostAsync("Account/ExternalLogin", content);
            Assert.Equal<string>("https://api.twitter.com/oauth/authenticate", response.Headers.Location.AbsoluteUri.Replace(response.Headers.Location.Query, string.Empty));
            var queryItems = new QueryCollection(QueryHelpers.ParseQuery(response.Headers.Location.Query));
            Assert.Equal<string>("custom", queryItems["custom_redirect_uri"]);
            Assert.Equal<string>("valid_oauth_token", queryItems["oauth_token"]);
            //Check for the correlation cookie
            Assert.NotNull(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri))["__TwitterState"]);

            //This is just to generate a correlation cookie. Previous step would generate this cookie, but we have reset the handler now.
            _httpClientHandler = new HttpClientHandler() { AllowAutoRedirect = false };
            _httpClient = new HttpClient(_httpClientHandler) { BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri) };

            response = await _httpClient.GetAsync("Account/Login");
            responseContent = await response.Content.ReadAsStringAsync();
            formParameters = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("provider", "Twitter"),
                new KeyValuePair<string, string>("returnUrl", "/"),
                new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLogin")),
            };

            content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await _httpClient.PostAsync("Account/ExternalLogin", content);
            response = await _httpClient.GetAsync(response.Headers.Location);
            //Post a message to the Facebook middleware
            response = await _httpClient.GetAsync("signin-twitter?oauth_token=valid_oauth_token&oauth_verifier=valid_oauth_verifier");
            response = await _httpClient.GetAsync(response.Headers.Location);
            await ThrowIfResponseStatusNotOk(response);
            responseContent = await response.Content.ReadAsStringAsync();

            //Check correlation cookie not getting cleared after successful signin
            if (!Helpers.RunningOnMono)
            {
                Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri))["__TwitterState"]);
            }
            Assert.Equal(_deploymentResult.ApplicationBaseUri + "Account/ExternalLoginCallback?ReturnUrl=%2F", response.RequestMessage.RequestUri.AbsoluteUri);
            //Twitter does not give back the email claim for some reason. 
            //Assert.Contains("*****@*****.**", responseContent, StringComparison.OrdinalIgnoreCase);

            formParameters = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("Email", "*****@*****.**"),
                new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLoginConfirmation?ReturnUrl=%2F")),
            };

            content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await _httpClient.PostAsync("Account/ExternalLoginConfirmation", content);
            response = await _httpClient.GetAsync(response.Headers.Location);
            await ThrowIfResponseStatusNotOk(response);
            responseContent = await response.Content.ReadAsStringAsync();

            Assert.Contains(string.Format("Hello {0}!", "*****@*****.**"), responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("Log off", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie sent
            Assert.NotNull(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.Application"));
            Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.ExternalLogin"));
            _logger.LogInformation("Successfully signed in with user '{email}'", "*****@*****.**");

            _logger.LogInformation("Verifying if the middleware events were fired");
            //Check for a non existing item
            response = await _httpClient.GetAsync(string.Format("Admin/StoreManager/GetAlbumIdFromName?albumName={0}", "123"));
            //This action requires admin permissions. If events are fired this permission is granted
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            _logger.LogInformation("Middleware events were fired successfully");
        }
        public async Task LoginWithOpenIdConnect()
        {
            _httpClientHandler = new HttpClientHandler() { AllowAutoRedirect = false };
            _httpClient = new HttpClient(_httpClientHandler) { BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri) };

            var response = await _httpClient.GetAsync("Account/Login");
            await ThrowIfResponseStatusNotOk(response);
            var responseContent = await response.Content.ReadAsStringAsync();
            _logger.LogInformation("Signing in with OpenIdConnect account");
            var formParameters = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("provider", "OpenIdConnect"),
                new KeyValuePair<string, string>("returnUrl", "/"),
                new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLogin")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await _httpClient.PostAsync("Account/ExternalLogin", content);
            Assert.Equal<string>("https://login.windows.net/4afbc689-805b-48cf-a24c-d4aa3248a248/oauth2/authorize", response.Headers.Location?.AbsoluteUri.Replace(response.Headers.Location.Query, string.Empty));
            var queryItems = new QueryCollection(QueryHelpers.ParseQuery(response.Headers.Location?.Query));
            Assert.Equal<string>("c99497aa-3ee2-4707-b8a8-c33f51323fef", queryItems["client_id"]);
            Assert.Equal<string>("form_post", queryItems["response_mode"]);
            Assert.Equal<string>("code id_token", queryItems["response_type"]);
            Assert.Equal<string>("openid profile", queryItems["scope"]);
            Assert.Equal<string>("OpenIdConnect.AuthenticationProperties=ValidStateData", queryItems["state"]);
            Assert.NotNull(queryItems["nonce"]);
            Assert.NotNull(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(".AspNet.OpenIdConnect.Nonce.protectedString"));

            // This is just enable the auto-redirect.
            _httpClientHandler = new HttpClientHandler() { AllowAutoRedirect = true };
            _httpClient = new HttpClient(_httpClientHandler) { BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri) };
            _httpClientHandler.CookieContainer.Add(new Uri(_deploymentResult.ApplicationBaseUri), new Cookie(".AspNet.OpenIdConnect.Nonce.protectedString", "N"));

            //Post a message to the OpenIdConnect middleware
            var token = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("code", "AAABAAAAvPM1KaPlrEqdFSBzjqfTGGBtrTYVn589oKw4lLgJ6Svz0AhPVOJr0J2-Uu_KffGlqIbYlRAyxmt-vZ7VlSVdrWvOkNhK9OaAMaSD7LDoPbBTVMEkB0MdAgBTV34l2el-s8ZI02_9PvgQaORZs7n8eGaGbcoKAoxiDn2OcKuJVplXYgrGUwU4VpRaqe6RaNzuseM7qBFbLIv4Wps8CndE6W8ccmuu6EvGC6-H4uF9EZL7gU4nEcTcvkE4Qyt8do6VhTVfM1ygRNQgmV1BCig5t_5xfhL6-xWQdy15Uzn_Df8VSsyDXe8s9cxyKlqc_AIyLFy_NEiMQFUqjZWKd_rR3A8ugug15SEEGuo1kF3jMc7dVMdE6OF9UBd-Ax5ILWT7V4clnRQb6-CXB538DlolREfE-PowXYruFBA-ARD6rwAVtuVfCSbS0Zr4ZqfNjt6x8yQdK-OkdQRZ1thiZcZlm1lyb2EquGZ8Deh2iWBoY1uNcyjzhG-L43EivxtHAp6Y8cErhbo41iacgqOycgyJWxiB5J0HHkxD0nQ2RVVuY8Ybc9sdgyfKkkK2wZ3idGaRCdZN8Q9VBhWRXPDMqHWG8t3aZRtvJ_Xd3WhjNPJC0GpepUGNNQtXiEoIECC363o1z6PZC5-E7U3l9xK06BZkcfTOnggUiSWNCrxUKS44dNqaozdYlO5E028UgAEhJ4eDtcP3PZty-0j4j5Mw0F2FmyAA"),
                new KeyValuePair<string, string>("id_token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImtyaU1QZG1Cdng2OHNrVDgtbVBBQjNCc2VlQSJ9.eyJhdWQiOiJjOTk0OTdhYS0zZWUyLTQ3MDctYjhhOC1jMzNmNTEzMjNmZWYiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC80YWZiYzY4OS04MDViLTQ4Y2YtYTI0Yy1kNGFhMzI0OGEyNDgvIiwiaWF0IjoxNDIyMzk1NzYzLCJuYmYiOjE0MjIzOTU3NjMsImV4cCI6MTQyMjM5OTY2MywidmVyIjoiMS4wIiwidGlkIjoiNGFmYmM2ODktODA1Yi00OGNmLWEyNGMtZDRhYTMyNDhhMjQ4IiwiYW1yIjpbInB3ZCJdLCJvaWQiOiJmODc2YWJlYi1kNmI1LTQ0ZTQtOTcxNi02MjY2YWMwMTgxYTgiLCJ1cG4iOiJ1c2VyM0BwcmFidXJhamdtYWlsLm9ubWljcm9zb2Z0LmNvbSIsInN1YiI6IlBVZGhjbFA1UGdJalNVOVAxUy1IZWxEYVNGU2YtbVhWMVk2MC1LMnZXcXciLCJnaXZlbl9uYW1lIjoiVXNlcjMiLCJmYW1pbHlfbmFtZSI6IlVzZXIzIiwibmFtZSI6IlVzZXIzIiwidW5pcXVlX25hbWUiOiJ1c2VyM0BwcmFidXJhamdtYWlsLm9ubWljcm9zb2Z0LmNvbSIsIm5vbmNlIjoiNjM1NTc5OTI4NjM5NTE3NzE1Lk9UUmpPVFZrTTJFdE1EUm1ZUzAwWkRFM0xUaGhaR1V0WldabVpHTTRPRGt6Wkdaa01EUmxORGhrTjJNdE9XSXdNQzAwWm1Wa0xXSTVNVEl0TVRVd1ltUTRNemRtT1dJMCIsImNfaGFzaCI6IkZHdDN3Y1FBRGUwUFkxUXg3TzFyNmciLCJwd2RfZXhwIjoiNjY5MzI4MCIsInB3ZF91cmwiOiJodHRwczovL3BvcnRhbC5taWNyb3NvZnRvbmxpbmUuY29tL0NoYW5nZVBhc3N3b3JkLmFzcHgifQ.coAdCkdMgnslMHagdU8IBgH7Z0dilRdMfKytyqPJuTr6sbmbhrAoAj-KeGwbKgzrd-BeDk_rW47dntWuuAqGrAOGzxXvS2dcSWgoEKoXuDccIL5b4rIomRpfJpaeE-YwiU3usyRvoQCpHmtOa0g7xVilIj3_1-9ylMgRDY5qcrtQ_hEZlGuYyiCPR0dw8WmNU7r6PKObG-o3Yk_RbEBHjnaWxKoJwrVUEZUQOJDAvlr6ZYEmGTlD_BM0Rc_0fJZPU7A3uN9PHLw1atm-chN06IDXf23R33JI_xFuEZnj9HZQ_eIzNCl7GFmUryK3FFgYJpIbsI0BIFuksSikXz33IA"),
                new KeyValuePair<string, string>("state", "OpenIdConnect.AuthenticationProperties=ValidStateData"),
                new KeyValuePair<string, string>("session_state", "d0b59ffa-2df9-4d8c-b43a-2c410987f4ae")
            };

            response = await _httpClient.PostAsync(string.Empty, new FormUrlEncodedContent(token.ToArray()));
            await ThrowIfResponseStatusNotOk(response);
            responseContent = await response.Content.ReadAsStringAsync();
            Assert.Equal(_deploymentResult.ApplicationBaseUri + "Account/ExternalLoginCallback?ReturnUrl=%2F", response.RequestMessage.RequestUri.AbsoluteUri);

            formParameters = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("Email", "*****@*****.**"),
                new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLoginConfirmation?ReturnUrl=%2F")),
            };

            content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await _httpClient.PostAsync("Account/ExternalLoginConfirmation", content);
            await ThrowIfResponseStatusNotOk(response);
            responseContent = await response.Content.ReadAsStringAsync();

            Assert.Contains(string.Format("Hello {0}!", "*****@*****.**"), responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("Log off", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie sent
            Assert.NotNull(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.Application"));
            Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.ExternalLogin"));
            _logger.LogInformation("Successfully signed in with user '{email}'", "*****@*****.**");

            _logger.LogInformation("Verifying if the middleware events were fired");
            //Check for a non existing item
            response = await _httpClient.GetAsync(string.Format("Admin/StoreManager/GetAlbumIdFromName?albumName={0}", "123"));
            //This action requires admin permissions. If events are fired this permission is granted
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            _logger.LogInformation("Middleware events were fired successfully");

            _logger.LogInformation("Verifying the OpenIdConnect logout flow..");
            response = await _httpClient.GetAsync(string.Empty);
            await ThrowIfResponseStatusNotOk(response);
            responseContent = await response.Content.ReadAsStringAsync();
            ValidateLayoutPage(responseContent);
            formParameters = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/LogOff")),
            };

            content = new FormUrlEncodedContent(formParameters.ToArray());
            // Need a non-redirecting handler
            var handler = new HttpClientHandler() { AllowAutoRedirect = false };
            handler.CookieContainer.Add(new Uri(_deploymentResult.ApplicationBaseUri), _httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)));
            _httpClient = new HttpClient(handler) { BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri) };

            response = await _httpClient.PostAsync("Account/LogOff", content);
            Assert.Null(handler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.Application"));
            Assert.Equal<string>(
                "https://login.windows.net/4afbc689-805b-48cf-a24c-d4aa3248a248/oauth2/logout",
                response.Headers.Location.AbsoluteUri.Replace(response.Headers.Location.Query, string.Empty));
            queryItems = new QueryCollection(QueryHelpers.ParseQuery(response.Headers.Location.Query));
            Assert.Equal<string>(_deploymentResult.ApplicationBaseUri + "Account/Login", queryItems["post_logout_redirect_uri"]);
        }