예제 #1
0
        public async Task ActionParameter_ReadOnlyCollectionModel_WithPrefix_DoesNotGetBound()
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter      = new ParameterDescriptor()
            {
                Name        = "Address",
                BindingInfo = new BindingInfo
                {
                    BinderModelName = "prefix"
                },
                ParameterType = typeof(Person6)
            };
            var operationContext = ModelBindingTestHelper.GetOperationBindingContext(request =>
            {
                request.QueryString = QueryString.Create("prefix.Address[0].Street", "SomeStreet");
            });

            var modelState = new ModelStateDictionary();

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, modelState, operationContext);

            // Assert
            Assert.NotNull(modelBindingResult);
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var boundModel = Assert.IsType <Person6>(modelBindingResult.Model);

            Assert.NotNull(boundModel);
            Assert.NotNull(boundModel.Address);

            // Arrays should not be updated.
            Assert.Equal(0, boundModel.Address.Count());

            // ModelState
            Assert.True(modelState.IsValid);
            Assert.Empty(modelState.Keys);
        }
예제 #2
0
        public async Task TryUpdateModel_ExistingModelWithNoParameterlessConstructor_OverwritesBoundValues()
        {
            // Arrange
            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.QueryString = QueryString.Create("Street", "SomeStreet");
            });

            var modelState = testContext.ModelState;
            var model      = new AddressWithNoParameterlessConstructor(10)
            {
                Street = "DefaultStreet",
                City   = "Toronto",
            };
            var oldModel = model;

            // Act
            var result = await TryUpdateModelAsync(model, string.Empty, testContext);

            // Assert
            Assert.True(result);

            // Model
            Assert.Same(oldModel, model);
            Assert.Equal("SomeStreet", model.Street);
            Assert.Equal("Toronto", model.City);

            // ModelState
            Assert.True(modelState.IsValid);

            var entry = Assert.Single(modelState);

            Assert.Equal("Street", entry.Key);
            var state = entry.Value;

            Assert.Equal("SomeStreet", state.AttemptedValue);
            Assert.Equal("SomeStreet", state.RawValue);
            Assert.Empty(state.Errors);
            Assert.Equal(ModelValidationState.Valid, state.ValidationState);
        }
        public async Task TryUpdateModel_ExistingModel_WithPrefix_ValuesGetOverwritten()
        {
            // Arrange
            var operationContext = ModelBindingTestHelper.GetOperationBindingContext(request =>
            {
                request.QueryString = QueryString.Create("prefix.Street", "SomeStreet");
            });

            var modelState = operationContext.ActionContext.ModelState;
            var model      = new Address
            {
                Street = "DefaultStreet",
                City   = "Toronto",
            };
            var oldModel = model;

            // Act
            var result = await TryUpdateModel(model, "prefix", operationContext);

            // Assert
            Assert.True(result);

            // Model
            Assert.Same(oldModel, model);
            Assert.Equal("SomeStreet", model.Street);
            Assert.Equal("Toronto", model.City);

            // ModelState
            Assert.True(modelState.IsValid);

            var entry = Assert.Single(modelState);

            Assert.Equal("prefix.Street", entry.Key);
            var state = entry.Value;

            Assert.Equal("SomeStreet", state.AttemptedValue);
            Assert.Equal("SomeStreet", state.RawValue);
            Assert.Empty(state.Errors);
            Assert.Equal(ModelValidationState.Valid, state.ValidationState);
        }
예제 #4
0
        public async Task BindParameter_WithEmptyData_DoesNotBind(Type parameterType)
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter      = new ParameterDescriptor
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo(),

                ParameterType = parameterType
            };
            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.QueryString = QueryString.Create("Parameter1", "");
            });
            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext);

            // Assert

            // ModelBindingResult
            Assert.False(modelBindingResult.IsModelSet);

            // Model
            Assert.Null(modelBindingResult.Model);

            // ModelState
            Assert.False(modelState.IsValid);
            var key = Assert.Single(modelState.Keys);

            Assert.Equal("Parameter1", key);
            Assert.Equal("", modelState[key].AttemptedValue);
            Assert.Equal("", modelState[key].RawValue);
            var error = Assert.Single(modelState[key].Errors);

            Assert.Equal("The value '' is invalid.", error.ErrorMessage, StringComparer.Ordinal);
            Assert.Null(error.Exception);
        }
예제 #5
0
        /// <inheritdoc/>
        public string Create(HttpContext context, CommandCollection commands)
        {
            var sb = new StringBuilder(context.Request.Host.ToString());

            string pathBase = context.Request.PathBase.ToString();

            if (!string.IsNullOrWhiteSpace(pathBase))
            {
                sb.AppendFormat("{0}/", pathBase);
            }

            string path = context.Request.Path.ToString();

            if (!string.IsNullOrWhiteSpace(path))
            {
                sb.Append(path);
            }

            sb.Append(QueryString.Create(commands));

            return(sb.ToString().ToLowerInvariant());
        }
        protected override async Task <bool> HandleUnauthorizedAsync(ChallengeContext context)
        {
            if (!Options.LoginPath.HasValue)
            {
                return(await base.HandleUnauthorizedAsync(context));
            }

            var redirectUri = new AuthenticationProperties(context.Properties).RedirectUri;

            //try
            //{
            if (string.IsNullOrEmpty(redirectUri))
            {
                redirectUri = OriginalPathBase + Request.Path + Request.QueryString;
            }

            //var loginUri = Options.LoginPath + QueryString.Create(Options.ReturnUrlParameter, redirectUri);
            var tenantResolver = tenantResolverFactory.GetResolver();
            var loginUri       = Options.LoginPath + QueryString.Create(tenantResolver.ResolveReturnUrlParameter(Options.ReturnUrlParameter), redirectUri);

            //var redirectContext = new CookieApplyRedirectContext(Context, Options, BuildRedirectUri(loginUri));
            //Options.Notifications.ApplyRedirect(redirectContext);

            var redirectContext = new CookieRedirectContext(Context, Options, BuildRedirectUri(loginUri));
            await Options.Events.RedirectToLogin(redirectContext);

            //}
            //catch (Exception exception)
            //{
            //    var exceptionContext = new CookieExceptionContext(Context, Options,
            //        CookieExceptionContext.ExceptionLocation.Unauthorized, exception, ticket: null);
            //    await Options.Events.Exception(exceptionContext);
            //    if (exceptionContext.Rethrow)
            //    {
            //        throw;
            //    }
            //}
            return(true);
        }
예제 #7
0
        public void Configure(IApplicationBuilder app)
        {
            app.Run(async context =>
            {
                var dicts = new Dictionary <string, string>()
                {
                    ["id"]      = "10",
                    ["name"]    = "dody gunawinata",
                    ["date"]    = "2020/05/30",
                    ["date2"]   = "2020-05-30",
                    ["guid"]    = System.Guid.NewGuid().ToString(),
                    ["artist"]  = "Simon & Garfunkel",
                    ["formula"] = "10 = 10 * 1"
                };

                var queryString = QueryString.Create(dicts);

                context.Response.Headers.Add("Content-Type", "text/html");
                await context.Response.WriteAsync($@"<html>
                <head>
                    <link rel=""stylesheet"" href=""https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css"" />
                </head>
                <body class=""content"">
                <div class=""container"">
                <h1>Using QueryString.Create to get URL encoded query string</h1>
                <strong>Input</strong>
                ");
                await context.Response.WriteAsync("<ul>");
                foreach (var k in dicts)
                {
                    await context.Response.WriteAsync($"<li>{k.Key} = {k.Value}</li>");
                }
                await context.Response.WriteAsync("</ul>");
                await context.Response.WriteAsync("<strong>Output</strong><br/>");
                await context.Response.WriteAsync(queryString.Value);
                await context.Response.WriteAsync("</ul>");
                await context.Response.WriteAsync(@"</div></body></html>");
            });
        }
예제 #8
0
        public async Task <IActionResult> Authorize()
        {
            var request = HttpContext.GetOpenIddictServerRequest() ??
                          throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");

            // Retrieve the user principal stored in the authentication cookie.
            var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            // If the user principal can't be extracted, redirect the user to the login page.
            if (!result.Succeeded)
            {
                return(Challenge(
                           authenticationSchemes: CookieAuthenticationDefaults.AuthenticationScheme,
                           properties: new AuthenticationProperties
                {
                    RedirectUri = Request.PathBase + Request.Path + QueryString.Create(
                        Request.HasFormContentType ? Request.Form.ToList() : Request.Query.ToList())
                }));
            }

            // Create a new claims principal
            var claims = new List <Claim>
            {
                // 'subject' claim which is required
                new Claim(OpenIddictConstants.Claims.Subject, result.Principal.Identity.Name),
                new Claim("some claim", "some value").SetDestinations(OpenIddictConstants.Destinations.AccessToken),
                new Claim(OpenIddictConstants.Claims.Email, "some@email").SetDestinations(OpenIddictConstants.Destinations.IdentityToken)
            };

            var claimsIdentity = new ClaimsIdentity(claims, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);

            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

            // Set requested scopes (this is not done automatically)
            claimsPrincipal.SetScopes(request.GetScopes());

            // Signing in with the OpenIddict authentiction scheme trigger OpenIddict to issue a code (which can be exchanged for an access token)
            return(SignIn(claimsPrincipal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));
        }
예제 #9
0
        public static string UpdatePagerInUrl(this HttpRequest request, string key, string value)
        {
            var url      = request.Path;
            var queryKvp = request.Query.Select(kvp => new KeyValuePair <string, string>(kvp.Key, kvp.Value)).ToList();;

            var existingQs = queryKvp.Where(q => q.Key.Equals(key)).FirstOrDefault();

            if (existingQs.Equals(new KeyValuePair <string, string>()))
            {
                queryKvp.Add(new KeyValuePair <string, string>(key, value));
            }
            else
            {
                string newValue = value;
                queryKvp.Remove(existingQs);
                queryKvp.Add(new KeyValuePair <string, string>(key, newValue));
            }

            string queryString = QueryString.Create(queryKvp).ToUriComponent();

            return(WebUtility.UrlEncode(url + queryString));
        }
예제 #10
0
        public string GetEndpointUrl(string baseUrl, string token = null)
        {
            if (token == null)
            {
                return($"{baseUrl}/login");
            }

            var endpoint = Type switch
            {
                MessageType.Confirmation => "confirmEmail",
                _ => "changePassword"
            };

            var queryParams = new Dictionary <string, string>
            {
                { "token", token },
                { "email", Recipient }
            };

            return($"{baseUrl}/{endpoint}{QueryString.Create(queryParams)}");
        }
    }
예제 #11
0
        private static string GetUri(HttpContext context, IDictionary <string, string> commands)
        {
            var sb = new StringBuilder(context.Request.Host.ToString());

            string pathBase = context.Request.PathBase.ToString();

            if (!string.IsNullOrWhiteSpace(pathBase))
            {
                sb.AppendFormat("{0}/", pathBase);
            }

            string path = context.Request.Path.ToString();

            if (!string.IsNullOrWhiteSpace(path))
            {
                sb.Append(path);
            }

            sb.Append(QueryString.Create(commands));

            return(sb.ToString().ToLowerInvariant());
        }
예제 #12
0
        public void Test()
        {
            // arrange
            var context = new DefaultHttpContext();

            var req = context.Request;

            req.QueryString = QueryString.Create("model", "any");

            var logger = NullLoggerFactory.Instance.CreateLogger("Null Logger");

            // act
            var result      = (ObjectResult)_sut.Run(req, logger);
            var resultValue = result.Value.ToString() ?? "";

            _outputHelper.WriteLine("resultValue: " + resultValue);

            // assert
            Assert.Equal(200, result.StatusCode);

            Assert.StartsWith("Watch Details: Abc", resultValue);
        }
예제 #13
0
        public async Task ActionParameter_EnforcesBindRequired(int?input, bool isValid)
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name          = BindingAndValidationController.BindRequiredParamInfo.Name,
                ParameterType = typeof(int)
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                if (input.HasValue)
                {
                    request.QueryString = QueryString.Create(parameter.Name, input.Value.ToString());
                }
            });

            var modelState            = testContext.ModelState;
            var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
            var modelMetadata         = modelMetadataProvider
                                        .GetMetadataForParameter(BindingAndValidationController.BindRequiredParamInfo);

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(
                parameter,
                testContext,
                modelMetadataProvider,
                modelMetadata);

            // Assert
            Assert.Equal(input.HasValue, modelBindingResult.IsModelSet);
            Assert.Equal(isValid, modelState.IsValid);
            if (isValid)
            {
                Assert.Equal(input.Value, Assert.IsType <int>(modelBindingResult.Model));
            }
        }
    public async Task ActionParameter_NonSettableArrayModel_WithPrefix_DoesNotGetBound()
    {
        // Arrange
        var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
        var parameter       = new ParameterDescriptor()
        {
            Name        = "Address",
            BindingInfo = new BindingInfo()
            {
                BinderModelName = "prefix"
            },
            ParameterType = typeof(Person5)
        };

        var testContext = ModelBindingTestHelper.GetTestContext(request =>
        {
            request.QueryString = QueryString.Create("prefix.Address[0].Street", "SomeStreet");
        });

        var modelState = testContext.ModelState;

        // Act
        var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

        // Assert
        Assert.True(modelBindingResult.IsModelSet);

        // Model
        Assert.NotNull(modelBindingResult.Model);
        var boundModel = Assert.IsType <Person5>(modelBindingResult.Model);

        // Arrays should not be updated.
        Assert.Empty(boundModel.Address);

        // ModelState
        Assert.True(modelState.IsValid);
        Assert.Empty(modelState.Keys);
    }
        public async Task BindParameter_WithEmptyData_BindsMutableAndNullableObjects(Type parameterType)
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter      = new ParameterDescriptor
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo(),

                ParameterType = parameterType
            };
            var operationContext = ModelBindingTestHelper.GetOperationBindingContext(request =>
            {
                request.QueryString = QueryString.Create("Parameter1", string.Empty);
            });
            var modelState = new ModelStateDictionary();

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, modelState, operationContext);

            // Assert

            // ModelBindingResult
            Assert.NotNull(modelBindingResult);
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            Assert.Null(modelBindingResult.Model);

            // ModelState
            Assert.True(modelState.IsValid);
            var key = Assert.Single(modelState.Keys);

            Assert.Equal("Parameter1", key);
            Assert.Equal(string.Empty, modelState[key].Value.AttemptedValue);
            Assert.Equal(string.Empty, modelState[key].Value.RawValue);
            Assert.Empty(modelState[key].Errors);
        }
        public async Task <IActionResult> Authorize()
        {
            OpenIddictRequest?request = HttpContext.GetOpenIddictServerRequest() ??
                                        throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");

            // Retrieve the user principal stored in the authentication cookie.
            var result = await HttpContext.AuthenticateAsync(IdentityConstants.ApplicationScheme);

            // If the user principal can't be extracted, redirect the user to the login page.
            if (result?.Succeeded != true)
            {
                return(Challenge(authenticationSchemes: IdentityConstants.ApplicationScheme,
                                 properties: new AuthenticationProperties
                {
                    RedirectUri = Request.PathBase + Request.Path +
                                  QueryString.Create(Request.HasFormContentType ? Request.Form.ToList() : Request.Query.ToList()),
                }));
            }

            // Retrieve the profile of the logged in user.
            var user = await this.userManager.GetUserAsync(User) ??
                       throw new InvalidOperationException("The user details cannot be retrieved.");

            // Create a new ClaimsPrincipal containing the claims that
            // will be used to create an id_token, a token or a code.
            var principal = await this.signInManager.CreateUserPrincipalAsync(user);

            // Set requested scopes (this is not done automatically)
            principal.SetScopes(request.GetScopes());

            foreach (var claim in principal.Claims)
            {
                claim.SetDestinations(GetDestinations(claim, principal));
            }

            // Signing in with the OpenIddict authentiction scheme trigger OpenIddict to issue a code (which can be exchanged for an access token)
            return(SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));
        }
            public async Task <IEnumerable <Media> > Handle(GetMediaByArrayOfIdsQuery query, CancellationToken cancellationToken)
            {
                var mediaIds = query.Ids.Select(x => new KeyValuePair <string, string>("mediaIds", x)).ToList();

                var accessToken = await _httpContextAcessor.HttpContext.GetTokenAsync("access_token");


                string uri         = $"multi";
                var    queryString = $"{uri}{QueryString.Create(mediaIds).ToString()}";

                _httpClient.SetBearerToken(accessToken);

                var response = await _httpClient.GetAsync(queryString);

                if (response.StatusCode.Equals(HttpStatusCode.NoContent))
                {
                    return(JsonSerializer.Deserialize <IEnumerable <Media> >("[]", DefaultJsonSettings.Settings));
                }

                var content = await response.Content.ReadAsStringAsync();

                return(JsonSerializer.Deserialize <IEnumerable <Media> >(content, DefaultJsonSettings.Settings));
            }
예제 #18
0
        /// <summary>
        /// Verifica se o recaptcha é valido usando a google API recaptcha
        /// </summary>
        /// <param name="recaptchaSecretKey"> Key do recaptcha para a aplicação</param>
        /// <param name="recaptcha">Valor informado pelo usuario ao concluir o chalenge do recaptcha na tela.</param>
        /// <param name="recaptchaUrlValidator">Url para validação do recaptcha no google</param>
        /// <returns>
        /// Verdadeiro (true) se o recapcha for válido ou Falso (false) para inválido.
        /// </returns>
        public static async Task <bool> ValidateRecaptcha(string recaptchaUrlValidator, string recaptchaSecretKey, string recaptcha)
        {
            var queryString = QueryString.Create(new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("response", recaptcha),
                new KeyValuePair <string, string>("secret", recaptchaSecretKey)
            });

            var url = recaptchaUrlValidator + queryString.ToUriComponent();

            var response = await _httpClient.PostAsync(url, null);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                return(false);
            }

            var responseBody = await response.Content.ReadAsStringAsync();

            var responseObj = JsonConvert.DeserializeObject <RecaptchaValidationResult>(responseBody);

            return(responseObj.Success);
        }
        public FilterContextBuilder()
        {
            httpContextMock  = new Mock <HttpContext>();
            httpRequestMock  = new Mock <HttpRequest>();
            headerDictionary = new HeaderDictionary();
            queryDictionary  = new Dictionary <string, StringValues>();
            queryCollection  = new QueryCollection(queryDictionary);
            actionArguments  = new Dictionary <string, object>();

            httpRequestMock.Setup(x => x.IsHttps).Returns(false);
            httpRequestMock.Setup(x => x.Body).Returns(new MemoryStream());
            httpRequestMock.Setup(x => x.Scheme).Returns("http");
            httpRequestMock.Setup(x => x.Host).Returns(new HostString("localhost"));
            httpRequestMock.Setup(x => x.PathBase).Returns(new PathString(""));
            httpRequestMock.Setup(x => x.Path).Returns(new PathString("/api/fake"));
            httpRequestMock.Setup(x => x.Headers).Returns(headerDictionary);
            httpRequestMock.Setup(x => x.Query).Returns(queryCollection);
            httpRequestMock.Setup(x => x.Body).Returns(new MemoryStream());
            httpRequestMock.Setup(x => x.QueryString).Returns(QueryString.Create(queryDictionary));

            httpContextMock.Setup(x => x.Request).Returns(httpRequestMock.Object);
            httpContextMock.Setup(x => x.Response.StatusCode).Returns(200);
        }
예제 #20
0
        public async Task <IActionResult> GetHouses(long type, int page, int limit)
        {
            List <KeyValuePair <string, string> > list = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>(nameof(page), page.ToString()),
                new KeyValuePair <string, string>(nameof(limit), limit.ToString())
            };

            if (type > 0)
            {
                list.Add(new KeyValuePair <string, string>("typeId", type.ToString()));
            }

            QueryString query = QueryString.Create(list);
            ResultModel model = await GetAsync <ResultModel>(query, _url.House.ListHouses);

            var data = JsonConvert.DeserializeObject <LayuiTableModel <HouseListModel> >(model.Data.ToString());

            data.StatusCode     = model.Status;
            data.Message        = model.Message;
            Response.StatusCode = model.Status;
            return(Json(data));
        }
예제 #21
0
        public async Task BindParameter_WithEmptyData_BindsReferenceAndNullableObjects(Type parameterType)
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo(),

                ParameterType = parameterType
            };
            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.QueryString = QueryString.Create("Parameter1", string.Empty);
            });
            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert

            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            Assert.Null(modelBindingResult.Model);

            // ModelState
            Assert.True(modelState.IsValid);
            var key = Assert.Single(modelState.Keys);

            Assert.Equal("Parameter1", key);
            Assert.Equal(string.Empty, modelState[key].AttemptedValue);
            Assert.Equal(string.Empty, modelState[key].RawValue);
            Assert.Empty(modelState[key].Errors);
        }
        public async Task TryUpdateModel_SettableArrayModel_WithPrefix_CreatesArray()
        {
            // Arrange
            var operationContext = ModelBindingTestHelper.GetOperationBindingContext(request =>
            {
                request.QueryString = QueryString.Create("prefix.Address[0].Street", "SomeStreet");
            });

            var modelState = new ModelStateDictionary();
            var model      = new Person4();

            // Act
            var result = await TryUpdateModel(model, "prefix", operationContext, modelState);

            // Assert
            Assert.True(result);

            // Model
            Assert.NotNull(model.Address);
            Assert.Equal(1, model.Address.Length);
            Assert.Equal("SomeStreet", model.Address[0].Street);
            Assert.Null(model.Address[0].City);

            // ModelState
            Assert.True(modelState.IsValid);

            var entry = Assert.Single(modelState);

            Assert.Equal("prefix.Address[0].Street", entry.Key);
            var state = entry.Value;

            Assert.NotNull(state.Value);
            Assert.Equal("SomeStreet", state.Value.AttemptedValue);
            Assert.Equal("SomeStreet", state.Value.RawValue);
            Assert.Empty(state.Errors);
            Assert.Equal(ModelValidationState.Valid, state.ValidationState);
        }
예제 #23
0
        private async Task <string> GetSecretAccessKeyFromServerAsync(string accessKeyId)
        {
            var builder = new UriBuilder(Options.Endpoint)
            {
                Query = QueryString.Create("accessKey", accessKeyId).Value
            };

            try
            {
                var req  = new HttpRequestMessage(HttpMethod.Get, builder.Uri);
                var resp = await Backchannel.SendAsync(req).ConfigureAwait(false);

                resp.EnsureSuccessStatusCode();

                var secret = await resp.Content.ReadAsStringAsync().ConfigureAwait(false);

                return(secret);
            }
            catch (Exception e)
            {
                _logger.LogError(898, e, "从服务器获取用户访问密钥失败, 请求地址:" + builder.Uri);
                return(null);
            }
        }
예제 #24
0
        public async Task TryUpdateModel_ExistingModel_WithPrefix_GetsOverWritten()
        {
            // Arrange
            var operationContext = ModelBindingTestHelper.GetOperationBindingContext(request =>
            {
                request.QueryString = QueryString.Create("prefix.Street", "SomeStreet");
            });

            var modelState = new ModelStateDictionary();
            var model      = new Address {
                Street = "DefaultStreet"
            };
            var oldModel = model;

            // Act
            var result = await TryUpdateModel(model, "prefix", operationContext, modelState);

            // Assert
            Assert.True(result);

            // Model
            Assert.Same(oldModel, model);
            Assert.Equal("SomeStreet", model.Street);

            // ModelState
            Assert.True(modelState.IsValid);

            Assert.Equal(1, modelState.Keys.Count);
            var key = Assert.Single(modelState.Keys, k => k == "prefix.Street");

            Assert.NotNull(modelState[key].Value);
            Assert.Equal("SomeStreet", modelState[key].Value.AttemptedValue);
            Assert.Equal("SomeStreet", modelState[key].Value.RawValue);
            Assert.Empty(modelState[key].Errors);
            Assert.Equal(ModelValidationState.Valid, modelState[key].ValidationState);
        }
        private async Task <UserApplicationAuthentication> GetUserFromServer(string accessKey)
        {
            var builder = new UriBuilder(Options.Authority)
            {
                Query = QueryString.Create("accessKey", accessKey).Value
            };
            var req  = new HttpRequestMessage(HttpMethod.Get, builder.Uri);
            var resp = await Backchannel.SendAsync(req).ConfigureAwait(false);

            try
            {
                resp.EnsureSuccessStatusCode();
                var model =
                    JsonConvert.DeserializeObject <UserApplicationAuthentication>(
                        await resp.Content.ReadAsStringAsync());

                return(model);
            }
            catch (Exception e)
            {
                Logger.LogError(899, e, "未能正确识别企业账号信息");
                return(null);
            }
        }
예제 #26
0
        public IActionResult RedirectToClickView()
        {
            var clientId  = _configuration.GetValue <string>("clientId");
            var secretKey = _configuration.GetValue <string>("secretKey");

            const string redirectUri = "https://localhost:5001/postback";
            const string connectUrl  = "https://online.clickview.com.au/v1/connect";

            var requestParams = new Dictionary <string, string>
            {
                { "client_id", clientId },
                { "redirect_uri", redirectUri }
            };

            var signature = SignatureGenerator.Generate(requestParams, secretKey);

            requestParams.Add("signature", signature);

            var url = connectUrl + QueryString.Create(requestParams);

            _logger.LogInformation("Redirecting to {Url}", url);

            return(Redirect(url));
        }
        public async Task TryUpdateModel_SettableCollectionModel_WithPrefix_CreatesCollection()
        {
            // Arrange
            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.QueryString = QueryString.Create("prefix.Address[0].Street", "SomeStreet");
            });

            var modelState = testContext.ModelState;
            var model      = new Person2();

            // Act
            var result = await TryUpdateModelAsync(model, "prefix", testContext);

            // Assert
            Assert.True(result);

            // Model
            Assert.NotNull(model.Address);
            Assert.Single(model.Address);
            Assert.Equal("SomeStreet", model.Address[0].Street);
            Assert.Null(model.Address[0].City);

            // ModelState
            Assert.True(modelState.IsValid);

            var entry = Assert.Single(modelState);

            Assert.Equal("prefix.Address[0].Street", entry.Key);
            var state = entry.Value;

            Assert.Equal("SomeStreet", state.AttemptedValue);
            Assert.Equal("SomeStreet", state.RawValue);
            Assert.Empty(state.Errors);
            Assert.Equal(ModelValidationState.Valid, state.ValidationState);
        }
    public async Task ActionParameter_UsingComplexTypeModelBinder_ModelPropertyTypeWithNoParameterlessConstructor_ThrowsException()
    {
        // Arrange
        var parameterType   = typeof(Class1);
        var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
        var parameter       = new ParameterDescriptor()
        {
            Name          = "p",
            ParameterType = parameterType
        };
        var testContext = ModelBindingTestHelper.GetTestContext(request =>
        {
            request.QueryString = QueryString.Create("Name", "James").Add("Property1.City", "Seattle");
        }, updateOptions: options =>
        {
            options.ModelBinderProviders.RemoveType <ComplexObjectModelBinderProvider>();
#pragma warning disable CS0618 // Type or member is obsolete
            options.ModelBinderProviders.Add(new ComplexTypeModelBinderProvider());
#pragma warning restore CS0618 // Type or member is obsolete
        });
        var modelState = testContext.ModelState;

        // Act & Assert
        var exception = await Assert.ThrowsAsync <InvalidOperationException>(() => parameterBinder.BindModelAsync(parameter, testContext));

        Assert.Equal(
            string.Format(
                CultureInfo.CurrentCulture,
                "Could not create an instance of type '{0}'. Model bound complex types must not be abstract or " +
                "value types and must have a parameterless constructor. Alternatively, set the '{1}' property to" +
                " a non-null value in the '{2}' constructor.",
                typeof(ClassWithNoDefaultConstructor).FullName,
                nameof(Class1.Property1),
                typeof(Class1).FullName),
            exception.Message);
    }
예제 #29
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.ApplicationServices.GetService <DiscordClientProvider>();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseMyExceptionHandler();
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            app.UseCookiePolicy(new CookiePolicyOptions()
            {
                MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None,
                Secure = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always
            });

            app.Use(async(context, next) =>
            {
                if (!context.Request.Cookies.ContainsKey("GenericUserId"))
                {
                    using RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();

                    byte[] random_seq = new byte[64];
                    rngCsp.GetBytes(random_seq);

                    string random_string = Convert.ToBase64String(random_seq);

                    context.Response.Cookies.Append("GenericUserId", random_string);

                    context.Items.Add("GenericUserId", random_string);
                }

                await next();
            });

            app.Use(async(context, next) =>
            {
                if (context.Request.Path == "/discord-callback")
                {
                    IQueryCollection query = context.Request.Query;

                    if (query.ContainsKey("state"))
                    {
                        try
                        {
                            DiscordCallbackState callbackState = JsonSerializer.Deserialize <DiscordCallbackState>(query["state"]);

                            if (!String.IsNullOrEmpty(callbackState.InternalRedirect))
                            {
                                QueryString redirectQuery = QueryString.Create(query.Where(p => p.Key != "state"));
                                redirectQuery             = redirectQuery.Add("state", callbackState.State);

                                context.Response.Redirect(context.Request.Scheme + "://" + context.Request.Host.Value
                                                          + callbackState.InternalRedirect + redirectQuery.Value);

                                return;
                            }
                        }
                        catch
                        {
                        }
                    }
                }

                await next();
            });

            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapFallbackToPage("/Index");
            });

#if DEBUG
            try
            {
                File.WriteAllText("update.browserlink", DateTime.Now.ToString());
            }
            catch
            {
            }
#endif
        }
        public async Task <IActionResult> Authorize()
        {
            var request = HttpContext.GetOpenIddictServerRequest() ??
                          throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");

            // Retrieve the user principal stored in the authentication cookie.
            // If it can't be extracted, redirect the user to the login page.
            var result = await HttpContext.AuthenticateAsync(IdentityConstants.ApplicationScheme);

            if (result is null || !result.Succeeded)
            {
                // If the client application requested promptless authentication,
                // return an error indicating that the user is not logged in.
                if (request.HasPrompt(Prompts.None))
                {
                    return(Forbid(
                               authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                               properties: new AuthenticationProperties(new Dictionary <string, string>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.LoginRequired,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The user is not logged in."
                    })));
                }

                return(Challenge(
                           authenticationSchemes: IdentityConstants.ApplicationScheme,
                           properties: new AuthenticationProperties
                {
                    RedirectUri = Request.PathBase + Request.Path + QueryString.Create(
                        Request.HasFormContentType ? Request.Form.ToList() : Request.Query.ToList())
                }));
            }

            // If prompt=login was specified by the client application,
            // immediately return the user agent to the login page.
            if (request.HasPrompt(Prompts.Login))
            {
                // To avoid endless login -> authorization redirects, the prompt=login flag
                // is removed from the authorization request payload before redirecting the user.
                var prompt = string.Join(" ", request.GetPrompts().Remove(Prompts.Login));

                var parameters = Request.HasFormContentType ?
                                 Request.Form.Where(parameter => parameter.Key != Parameters.Prompt).ToList() :
                                 Request.Query.Where(parameter => parameter.Key != Parameters.Prompt).ToList();

                parameters.Add(KeyValuePair.Create(Parameters.Prompt, new StringValues(prompt)));

                return(Challenge(
                           authenticationSchemes: IdentityConstants.ApplicationScheme,
                           properties: new AuthenticationProperties
                {
                    RedirectUri = Request.PathBase + Request.Path + QueryString.Create(parameters)
                }));
            }

            // If a max_age parameter was provided, ensure that the cookie is not too old.
            // If it's too old, automatically redirect the user agent to the login page.
            if (request.MaxAge is not null && result.Properties?.IssuedUtc is not null &&
                DateTimeOffset.UtcNow - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value))
            {
                if (request.HasPrompt(Prompts.None))
                {
                    return(Forbid(
                               authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                               properties: new AuthenticationProperties(new Dictionary <string, string>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.LoginRequired,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The user is not logged in."
                    })));
                }

                return(Challenge(
                           authenticationSchemes: IdentityConstants.ApplicationScheme,
                           properties: new AuthenticationProperties
                {
                    RedirectUri = Request.PathBase + Request.Path + QueryString.Create(
                        Request.HasFormContentType ? Request.Form.ToList() : Request.Query.ToList())
                }));
            }

            // Retrieve the profile of the logged in user.
            var user = await _userProvider.GetUserAsync(result.Principal) ??
                       throw new InvalidOperationException("The user details cannot be retrieved.");

            // Retrieve the application details from the database.
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ??
                              throw new InvalidOperationException("Details concerning the calling client application cannot be found.");

            // Retrieve the permanent authorizations associated with the user and the calling client application.
            var authorizations = await _authorizationManager.FindAsync(
                subject : await _userProvider.GetUserIdAsync(user),
                client : await _applicationManager.GetIdAsync(application),
                status : Statuses.Valid,
                type : AuthorizationTypes.Permanent,
                scopes : request.GetScopes()).ToListAsync();

            switch (await _applicationManager.GetConsentTypeAsync(application))
            {
            // If the consent is external (e.g when authorizations are granted by a sysadmin),
            // immediately return an error if no authorization can be found in the database.
            case ConsentTypes.External when !authorizations.Any():
                return(Forbid(
                           authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                           properties: new AuthenticationProperties(new Dictionary <string, string>
                {
                    [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired,
                    [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
                        "The logged in user is not allowed to access this client application."
                })));

            // If the consent is implicit or if an authorization was found,
            // return an authorization response without displaying the consent form.
            case ConsentTypes.Implicit:
            case ConsentTypes.External when authorizations.Any():
            case ConsentTypes.Explicit when authorizations.Any() && !request.HasPrompt(Prompts.Consent):
                var principal = await _userProvider.CreateUserPrincipalAsync(user);

                // Note: in this sample, the granted scopes match the requested scope
                // but you may want to allow the user to uncheck specific scopes.
                // For that, simply restrict the list of scopes before calling SetScopes.
                principal.SetScopes(request.GetScopes());
                principal.SetResources(await _scopeManager.ListResourcesAsync(principal.GetScopes()).ToListAsync());

                // Automatically create a permanent authorization to avoid requiring explicit consent
                // for future authorization or token requests containing the same scopes.
                var authorization = authorizations.LastOrDefault();
                if (authorization is null)
                {
                    authorization = await _authorizationManager.CreateAsync(
                        principal : principal,
                        subject : await _userProvider.GetUserIdAsync(user),
                        client : await _applicationManager.GetIdAsync(application),
                        type : AuthorizationTypes.Permanent,
                        scopes : principal.GetScopes());
                }

                principal.SetAuthorizationId(await _authorizationManager.GetIdAsync(authorization));

                foreach (var claim in principal.Claims)
                {
                    claim.SetDestinations(GetDestinations(claim, principal));
                }

                return(SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));

            // At this point, no authorization was found in the database and an error must be returned
            // if the client application specified prompt=none in the authorization request.
            case ConsentTypes.Explicit when request.HasPrompt(Prompts.None):
            case ConsentTypes.Systematic when request.HasPrompt(Prompts.None):
                return(Forbid(
                           authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                           properties: new AuthenticationProperties(new Dictionary <string, string>
                {
                    [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired,
                    [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
                        "Interactive user consent is required."
                })));

            // In every other case, render the consent form.
            default:
                return(View(new AuthorizeViewModel
                {
                    ApplicationName = await _applicationManager.GetLocalizedDisplayNameAsync(application),
                    Scope = request.Scope
                }));
            }
        }