private Uri GetRequestUri <T>(UpdateCommand <T> command)
        {
            string requestUri = this.GetMessageBase <T>();

            if (command.ParameterKey == Parameters.Id)
            {
                requestUri += $"/{command.ParameterValue}";
            }
            else if (!string.IsNullOrEmpty(command.ParameterKey) && command.ParameterValue != null)
            {
                requestUri += $"/{command.ParameterKey}={command.ParameterValue}";
            }

            List <KeyValuePair <string, string> > queryStringParameters = new List <KeyValuePair <string, string> >();

            if (command.Expand != null)
            {
                queryStringParameters.AddRange(command.Expand.Select(x => new KeyValuePair <string, string>("expand", x)));
            }

            queryStringParameters.AddRange(this.GetAdditionalParameters(command.AdditionalParameters));
            queryStringParameters.ForEach(x => { requestUri = QueryHelpers.AddQueryString(requestUri, x.Key, x.Value); });
            return(new Uri(requestUri, UriKind.Relative));
        }
Example #2
0
        public async Task Sending_client_credentials_in_body_should_succeed()
        {
            _options.ClientSecret = "secret";
            _options.TokenClientCredentialStyle = Client.ClientCredentialStyle.PostBody;

            var client = new OidcClient(_options);
            var state  = await client.PrepareLoginAsync();

            var url     = $"?state={state.State}&nonce={state.Nonce}&code=bar";
            var key     = Crypto.CreateKey();
            var idToken = Crypto.CreateJwt(key, "https://authority", "client",
                                           new Claim("at_hash", Crypto.HashData("token")),
                                           new Claim("sub", "123"),
                                           new Claim("nonce", state.Nonce));

            var tokenResponse = new Dictionary <string, object>
            {
                { "access_token", "token" },
                { "expires_in", 300 },
                { "id_token", idToken },
                { "refresh_token", "refresh_token" }
            };

            _options.ProviderInformation.KeySet = Crypto.CreateKeySet(key);

            var backChannelHandler = new NetworkHandler(JsonSerializer.Serialize(tokenResponse), HttpStatusCode.OK);

            _options.BackchannelHandler = backChannelHandler;

            var result = await client.ProcessResponseAsync(url, state);

            var fields = QueryHelpers.ParseQuery(backChannelHandler.Body);

            fields["client_id"].First().Should().Be("client");
            fields["client_secret"].First().Should().Be("secret");
        }
Example #3
0
        public Uri GetPageUri(PaginationFilterDetailSearch filter, string route)
        {
            var _enpointUri = new Uri(string.Concat(_baseUri, route));
            var modifiedUri = QueryHelpers.AddQueryString(_enpointUri.ToString(), "pageNumber", filter.PageNumber.ToString());

            //modifiedUri = QueryHelpers.AddQueryString(modifiedUri, "pageNumber", filter.PageNumber.ToString());
            modifiedUri = QueryHelpers.AddQueryString(modifiedUri, "pageSize", filter.PageSize.ToString());
            if (!string.IsNullOrEmpty(filter.Search?.FirstName))
            {
                modifiedUri = QueryHelpers.AddQueryString(modifiedUri, nameof(filter.Search) + "." + nameof(filter.Search.FirstName), filter.Search.FirstName.ToString());
            }
            if (!string.IsNullOrEmpty(filter.Search?.LastName))
            {
                modifiedUri = QueryHelpers.AddQueryString(modifiedUri, nameof(filter.Search) + "." + nameof(filter.Search.LastName), filter.Search.LastName.ToString());
            }
            if (!string.IsNullOrEmpty(filter.Search?.PersonalNumber))
            {
                modifiedUri = QueryHelpers.AddQueryString(modifiedUri, nameof(filter.Search) + "." + nameof(filter.Search.PersonalNumber), filter.Search.PersonalNumber.ToString());
            }
            if (!string.IsNullOrEmpty(filter.Search?.City?.Name))
            {
                modifiedUri = QueryHelpers.AddQueryString(modifiedUri, nameof(filter.Search) + "." + nameof(filter.Search.City.Name), filter.Search.City?.Name.ToString());
            }
            if (!string.IsNullOrEmpty(filter.Search?.BirthDate.ToString()) && filter.Search.BirthDate != DateTime.MinValue && filter.Search.BirthDate != default(DateTime))
            {
                modifiedUri = QueryHelpers.AddQueryString(modifiedUri, nameof(filter.Search) + "." + nameof(filter.Search.BirthDate), filter.Search.BirthDate.ToString());
            }
            if (filter.Search?.Gender != null)
            {
                if (Enum.IsDefined(typeof(Gender), filter.Search.Gender))
                {
                    modifiedUri = QueryHelpers.AddQueryString(modifiedUri, nameof(filter.Search) + "." + nameof(filter.Search.Gender), filter.Search.Gender.ToString());
                }
            }
            return(new Uri(modifiedUri));
        }
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public async Task PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //create common query parameters for the request
            var queryParameters = await CreateQueryParameters(postProcessPaymentRequest);

            //whether to include order items in a transaction
            if (_paypalStandardPaymentSettings.PassProductNamesAndTotals)
            {
                //add order items query parameters to the request
                var parameters = new Dictionary <string, string>(queryParameters);
                await AddItemsParameters(parameters, postProcessPaymentRequest);

                //remove null values from parameters
                parameters = parameters.Where(parameter => !string.IsNullOrEmpty(parameter.Value))
                             .ToDictionary(parameter => parameter.Key, parameter => parameter.Value);

                //ensure redirect URL doesn't exceed 2K chars to avoid "too long URL" exception
                var redirectUrl = QueryHelpers.AddQueryString(GetPaypalUrl(), parameters);
                if (redirectUrl.Length <= 2048)
                {
                    _httpContextAccessor.HttpContext.Response.Redirect(redirectUrl);
                    return;
                }
            }

            //or add only an order total query parameters to the request
            await AddOrderTotalParameters(queryParameters, postProcessPaymentRequest);

            //remove null values from parameters
            queryParameters = queryParameters.Where(parameter => !string.IsNullOrEmpty(parameter.Value))
                              .ToDictionary(parameter => parameter.Key, parameter => parameter.Value);

            var url = QueryHelpers.AddQueryString(GetPaypalUrl(), queryParameters);

            _httpContextAccessor.HttpContext.Response.Redirect(url);
        }
Example #5
0
        public Uri GetPagesUri(string route, string filter, PaginationQuery paginationQuery = null)
        {
            var uri = new Uri($"{_baseUri}{route}");

            if (paginationQuery is null)
            {
                return(uri);
            }

            if (filter is null)
            {
                return(uri);
            }


            var modifiedUri =
                QueryHelpers.AddQueryString(uri.ToString(), "pageNumber", paginationQuery.PageNumber.ToString());

            modifiedUri = QueryHelpers.AddQueryString(modifiedUri, "pageSize", paginationQuery.PageSize.ToString());

            modifiedUri = $"{modifiedUri}&{filter}";

            return(new Uri(modifiedUri));
        }
        /// <inheritdoc />
        protected override string BuildChallengeUrl([NotNull] AuthenticationProperties properties, [NotNull] string redirectUri)
        {
            if (!properties.Items.TryGetValue(ShopifyAuthenticationDefaults.ShopNameAuthenticationProperty, out string?shopName))
            {
                string message =
                    $"Shopify provider AuthenticationProperties must contain {ShopifyAuthenticationDefaults.ShopNameAuthenticationProperty}.";

                Logger.LogError(message);
                throw new InvalidOperationException(message);
            }

            string uri = string.Format(CultureInfo.InvariantCulture, Options.AuthorizationEndpoint, shopName);

            // Get the permission scope, which can either be set in options or overridden in AuthenticationProperties.
            if (!properties.Items.TryGetValue(ShopifyAuthenticationDefaults.ShopScopeAuthenticationProperty, out string?scope))
            {
                scope = FormatScope();
            }

            string url = QueryHelpers.AddQueryString(uri, new Dictionary <string, string>()
            {
                ["client_id"]    = Options.ClientId,
                ["scope"]        = scope,
                ["redirect_uri"] = redirectUri,
                ["state"]        = Options.StateDataFormat.Protect(properties)
            });

            // If we're requesting a per-user, online only, token, add the grant_options query param.
            if (properties.Items.TryGetValue(ShopifyAuthenticationDefaults.GrantOptionsAuthenticationProperty, out string?grantOptions) &&
                grantOptions == ShopifyAuthenticationDefaults.PerUserAuthenticationPropertyValue)
            {
                url = QueryHelpers.AddQueryString(url, "grant_options[]", ShopifyAuthenticationDefaults.PerUserAuthenticationPropertyValue);
            }

            return(url);
        }
Example #7
0
        /// <summary>
        /// 通过Code获取Access Token(这是第二步)
        /// </summary>
        protected override async Task <OAuthTokenResponse> ExchangeCodeAsync(string code, string redirectUri)
        {
            var parameters = new Dictionary <string, string>
            {
                { "appid", Options.ClientId },
                { "secret", Options.ClientSecret },
                { "code", code },
                { "grant_type", "authorization_code" }
            };

            var endpoint = QueryHelpers.AddQueryString(Options.TokenEndpoint, parameters);

            var response = await Backchannel.GetAsync(endpoint, Context.RequestAborted);

            if (response.IsSuccessStatusCode)
            {
                var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
                return(OAuthTokenResponse.Success(payload));
            }
            else
            {
                return(OAuthTokenResponse.Failed(new Exception("获取微信AccessToken出错。")));
            }
        }
Example #8
0
        public async Task <IEnumerable <ContentResponse> > GetArticles(int take, int skip, string filter, string include)
        {
            var requestPath  = $"api/content/{_contentConfiguration.BogId}";
            var pathAndQuery = QueryHelpers.AddQueryString(requestPath, new Dictionary <string, string>()
            {
                { "take", $"{take}" },
                { "skip", $"{skip}" },
                { "filter", $"{filter}" },
                { "include", $"{include}" },
            });
            var request  = new HttpRequestMessage(HttpMethod.Get, pathAndQuery);
            var response = await SendAsync(request);

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception($"Error retrieving articles for route {pathAndQuery} : {response.StatusCode}");
            }

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

            var searchArticles = JsonSerializer.Deserialize <IEnumerable <ContentResponse> >(msgContent, _jsonOptions);

            return(searchArticles);
        }
        public static bool TryGetQueryString <T>(this NavigationManager navigationManager, string key, out T value)
        {
            var uri = navigationManager.ToAbsoluteUri(navigationManager.Uri);

            try
            {
                if (QueryHelpers.ParseQuery(uri.Query).TryGetValue(key, out var valueFromQueryString))
                {
                    var converter = TypeDescriptor.GetConverter(typeof(T));

                    value = (T)converter.ConvertFromString(valueFromQueryString);

                    return(true);
                }
            }
            catch
            {
                // ignored
            }

            value = default;

            return(false);
        }
        /// <summary>
        /// post异步请求接口数据,参数放在url里面
        /// </summary>
        /// <typeparam name="T">输出参数</typeparam>
        /// <param name="httpClient"></param>
        /// <param name="api"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static async Task <T> PostQueryAsync <T>(this HttpClient httpClient, string url, object data)
        {
            try
            {
                var dicts    = ParaToDictionary(data);
                var uri      = QueryHelpers.AddQueryString(url, dicts);
                var response = await httpClient.PostAsync(uri, new StringContent(""));

                if (response.IsSuccessStatusCode)//请求成功
                {
                    string str = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(str))
                    {
                        return(JsonConvert.DeserializeObject <T>(str));
                    }
                }
                return(default(T));
            }
            catch (Exception e)
            {
                return(default(T));
            }
        }
Example #11
0
        public async Task IntegrationTest2_GameServer_ApplicationLayer_JoinLobby_ResponseBadRequest()
        {
            //arrange

            _client.DefaultRequestHeaders.Add("username", _pers.Username);
            _client.DefaultRequestHeaders.Add("password", _pers.Password);
            _fakeUserRepository.GetItemAsync(_pers.Username).Returns(_pers);
            _fakeUserRepository.GetItemAsync(_pers2.Username).Returns(_pers2);

            var parameters = new Dictionary <string, string>()
            {
                { "lobbyId", "AwesomeTestLobby" }
            };

            var joinLobbyRequestUri = QueryHelpers.AddQueryString("api/Lobby/Join", parameters);

            var joinLobbyRequest = new HttpRequestMessage(HttpMethod.Post, joinLobbyRequestUri);


            //Log in
            var loginResponse = await _client.GetAsync("api/User/Login");

            //log in with new user
            _client.DefaultRequestHeaders.Remove("username");
            _client.DefaultRequestHeaders.Remove("password");
            _client.DefaultRequestHeaders.Add("username", _pers2.Username);
            _client.DefaultRequestHeaders.Add("password", _pers2.Password);

            loginResponse = await _client.GetAsync("api/User/Login");

            //JoinLobby
            HttpResponseMessage response = await _client.SendAsync(joinLobbyRequest);

            //assert
            Assert.That(response.StatusCode, Is.EqualTo(System.Net.HttpStatusCode.BadRequest));
        }
Example #12
0
        public static void RelativeUrl(this HttpContext context, string relativeUrl)
        {
            if (relativeUrl != null && relativeUrl.Contains("?"))
            {
                var parts = relativeUrl.Trim().Split('?');
                context.Request.Path = parts[0];

                if (parts[1].IsNotEmpty())
                {
                    var dict = QueryHelpers.ParseQuery(parts[1]);

                    var request = context.Request.As <StubHttpRequest>();

                    foreach (var pair in dict)
                    {
                        request.AddQueryString(pair.Key, pair.Value);
                    }
                }
            }
            else
            {
                context.Request.Path = relativeUrl;
            }
        }
        public int GetCurrentPageNo(
            string url,
            string pageParamName,
            int defaultPageNo = 1)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                throw new ArgumentNullException($"{nameof(url)} cannot be null or empty or whitespace.", nameof(url));
            }

            if (string.IsNullOrWhiteSpace(pageParamName))
            {
                throw new ArgumentNullException($"{nameof(pageParamName)} cannot be null or empty or whitespace.", nameof(pageParamName));
            }

            if (defaultPageNo < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(defaultPageNo), $"{nameof(defaultPageNo)} cannot be less than 1.");
            }

            var ub          = new UriBuilder(url);
            var query       = QueryHelpers.ParseQuery(ub.Query);
            var currentPage = defaultPageNo;

            if (query.ContainsKey(pageParamName))
            {
                var queryValue = query.GetValueOrDefault(pageParamName);

                if (int.TryParse(queryValue, out int parsed) && parsed > defaultPageNo)
                {
                    currentPage = parsed;
                }
            }

            return(currentPage);
        }
        // https://github.com/tiagodaraujo/HttpContextMoq/blob/master/src/HttpContextMoq/Extensions/ContextExtensions.cs
        public static void SetUrl(this Mock <HttpRequest> httpRequest, Uri url)
        {
            httpRequest.Setup(x => x.IsHttps).Returns(url.Scheme == "https");
            httpRequest.Setup(x => x.Scheme).Returns(url.Scheme);
            if ((url.Scheme == "https" && url.Port != 443) || (url.Scheme == "http" && url.Port != 80))
            {
                httpRequest.Setup(x => x.Host).Returns(new HostString(url.Host, url.Port));
            }
            else
            {
                httpRequest.Setup(x => x.Host).Returns(new HostString(url.Host));
            }

            httpRequest.Setup(x => x.PathBase).Returns(string.Empty);
            httpRequest.Setup(x => x.Path).Returns(url.AbsolutePath);

            var queryString = QueryString.FromUriComponent(url);

            httpRequest.Setup(x => x.QueryString).Returns(queryString);

            var queryDictionary = QueryHelpers.ParseQuery(queryString.ToString());

            httpRequest.Setup(p => p.Query).Returns(new CustomQueryCollection(queryDictionary));
        }
Example #15
0
        public async Task <double> AddressBalance(string walletAddress)
        {
            var queryParams = new Dictionary <string, string> {
                { "address", walletAddress }
            };

            using (var client = new BaseClient(_appConfiguration).SmartContractWalletCall())
            {
                var url = QueryHelpers.AddQueryString("address-balance", queryParams);

                var response = await client.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();

                    var responseData = JsonConvert.DeserializeObject <double>(content);

                    return(responseData);
                }

                return(0);
            }
        }
Example #16
0
        public async Task GetByQueryAsync_UsingNoJsonWebToken_ReturnsUnauthorizedHttpStatusCode()
        {
            // Arrange
            using HttpClient httpClient = webApplicationFactory.CreateClient();

            var queryString = new Dictionary <string, string>
            {
                { nameof(TodoItemQueryModel.PageIndex), 0.ToString() },
                { nameof(TodoItemQueryModel.PageSize), 5.ToString() },
                { nameof(TodoItemQueryModel.SortBy), nameof(TodoItem.CreatedOn) },
                { nameof(TodoItemQueryModel.IsSortAscending), bool.FalseString }
            };
            string requestUri = QueryHelpers.AddQueryString(BaseUrl, queryString);

            // Act
            HttpResponseMessage response = await httpClient.GetAsync(requestUri);

            // Assert
            using (new AssertionScope())
            {
                response.IsSuccessStatusCode.Should().BeFalse(BecauseCurrentRequestHasNoJwt);
                response.StatusCode.Should().Be(HttpStatusCode.Unauthorized, BecauseCurrentRequestHasNoJwt);
            }
        }
        public static bool TryGetQueryString(this NavigationManager navigationManager, string key, out int?value)
        {
            var          uri = navigationManager.ToAbsoluteUri(navigationManager.Uri);
            StringValues parseQueryResult;
            var          query             = QueryHelpers.ParseQuery(uri.Query);
            var          parseQuerySuccess = query.TryGetValue(key, out parseQueryResult);

            if (parseQuerySuccess)
            {
                int parseIntResult;
                var parseIntSuccess = int.TryParse(parseQueryResult, out parseIntResult);

                if (parseIntSuccess)
                {
                    value = parseIntResult;

                    return(true);
                }
            }

            value = null;

            return(false);
        }
Example #18
0
        public async Task <List <ShowingModel> > GetShowingsByIdAndDate(string id, DateTime date)
        {
            var query = new Dictionary <string, string>
            {
                ["id"]   = id.ToString(),
                ["date"] = date.ToString()
            };

            string uri = QueryHelpers.AddQueryString("/api/showing", query);

            using (HttpResponseMessage response = await _apiHelper.ApiClient.GetAsync(uri))
            {
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsAsync <List <ShowingModel> >();

                    return(result);
                }
                else
                {
                    throw new Exception(response.ReasonPhrase);
                }
            }
        }
        /// <summary>
        /// Extract OAUTH Options
        /// </summary>
        /// <param name="authProvider"></param>
        /// <param name="dataProtectionProvider"></param>
        /// <returns></returns>
        private OAuthOptions ExtractOAuthOptions(
            AuthenticationProviderResponse authProvider,
            IDataProtectionProvider dataProtectionProvider)
        {
            var clientId                = authProvider.Options.FirstOrDefault(o => o.Key == "ClientId");
            var clientSecret            = authProvider.Options.FirstOrDefault(o => o.Key == "ClientSecret");
            var authorizationEndPoint   = authProvider.Options.FirstOrDefault(o => o.Key == "AuthorizationEndpoint");
            var tokenEndpoint           = authProvider.Options.FirstOrDefault(o => o.Key == "TokenEndpoint");
            var userInformationEndpoint = authProvider.Options.FirstOrDefault(o => o.Key == "UserInformationEndpoint");
            var code      = authProvider.Code;
            var nameSpace = authProvider.Namespace;
            var className = authProvider.ClassName;

            var scopes = authProvider.Options.Where(o => o.Key == "Scope").ToList();

            if (clientId == null ||
                clientSecret == null ||
                string.IsNullOrWhiteSpace(code) ||
                string.IsNullOrWhiteSpace(nameSpace) ||
                string.IsNullOrWhiteSpace(className))
            {
                return(null);
            }

            var dataProtector = dataProtectionProvider.CreateProtector(
                typeof(AuthenticationManager).FullName, Constants.IdentityProviderNames.Microsoft, "v1");

            var result = new OAuthOptions
            {
                ClientId                = clientId.Value,
                ClientSecret            = clientSecret.Value,
                AuthenticationScheme    = authProvider.Name,
                DisplayName             = authProvider.Name,
                ClaimsIssuer            = authProvider.Name,
                SignInScheme            = Constants.CookieName,
                CallbackPath            = new PathString(authProvider.CallbackPath),
                AuthorizationEndpoint   = authorizationEndPoint.Value,
                TokenEndpoint           = tokenEndpoint.Value,
                UserInformationEndpoint = userInformationEndpoint.Value,
                StateDataFormat         = new PropertiesDataFormat(dataProtector),
                Events = new OAuthEvents
                {
                    OnCreatingTicket = async context =>
                    {
                        var endpoint = QueryHelpers.AddQueryString(context.Options.UserInformationEndpoint, "access_token", context.AccessToken);
                        var request  = new HttpRequestMessage(HttpMethod.Get, endpoint);
                        request.Headers.Add("User-Agent", "SimpleIdentityServer");
                        request.Headers.Add("Authorization", "Bearer " + context.AccessToken);
                        var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted);

                        response.EnsureSuccessStatusCode();
                        var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
                        var claims  = _claimsParser.Parse(nameSpace, className, code, payload);
                        foreach (var claim in claims)
                        {
                            context.Identity.AddClaim(claim);
                        }
                    }
                }
            };

            result.Scope.Clear();
            if (scopes != null)
            {
                foreach (var scope in scopes.Select(s => s.Value))
                {
                    result.Scope.Add(scope);
                }
            }

            return(result);
        }
 public static IDictionary <string, StringValues> ParseQueryString(string queryString)
 {
     return(QueryHelpers.ParseQuery(queryString));
 }
        private void LoginWithTwitter()
        {
            _httpClientHandler = new HttpClientHandler()
            {
                AllowAutoRedirect = false
            };
            _httpClient = new HttpClient(_httpClientHandler)
            {
                BaseAddress = new Uri(_applicationBaseUrl)
            };

            var response = _httpClient.GetAsync("Account/Login").Result;

            ThrowIfResponseStatusNotOk(response);
            var responseContent = response.Content.ReadAsStringAsync().Result;

            _logger.WriteInformation("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 = _httpClient.PostAsync("Account/ExternalLogin", content).Result;
            Assert.Equal <string>("https://twitter.com/oauth/authenticate", response.Headers.Location.AbsoluteUri.Replace(response.Headers.Location.Query, string.Empty));
            var queryItems = new ReadableStringCollection(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(_applicationBaseUrl))["__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 = true
            };
            _httpClient = new HttpClient(_httpClientHandler)
            {
                BaseAddress = new Uri(_applicationBaseUrl)
            };

            response        = _httpClient.GetAsync("Account/Login").Result;
            responseContent = response.Content.ReadAsStringAsync().Result;
            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 = _httpClient.PostAsync("Account/ExternalLogin", content).Result;

            //Post a message to the Facebook middleware
            response = _httpClient.GetAsync("signin-twitter?oauth_token=valid_oauth_token&oauth_verifier=valid_oauth_verifier").Result;
            ThrowIfResponseStatusNotOk(response);
            responseContent = response.Content.ReadAsStringAsync().Result;

            //Check correlation cookie not getting cleared after successful signin
            if (!Helpers.RunningOnMono)
            {
                Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_applicationBaseUrl))["__TwitterState"]);
            }
            Assert.Equal(_applicationBaseUrl + "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 = _httpClient.PostAsync("Account/ExternalLoginConfirmation", content).Result;
            ThrowIfResponseStatusNotOk(response);
            responseContent = response.Content.ReadAsStringAsync().Result;

            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(_applicationBaseUrl)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.Application"));
            Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_applicationBaseUrl)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.ExternalLogin"));
            _logger.WriteInformation("Successfully signed in with user '{0}'", "*****@*****.**");

            _logger.WriteInformation("Verifying if the middleware notifications were fired");
            //Check for a non existing item
            response = _httpClient.GetAsync(string.Format("Admin/StoreManager/GetAlbumIdFromName?albumName={0}", "123")).Result;
            //This action requires admin permissions. If notifications are fired this permission is granted
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            _logger.WriteInformation("Middleware notifications were fired successfully");
        }
Example #22
0
 private static string GetReleaseGuid(string url, IElement tabNode)
 {
     // Appending id to differentiate between different quality versions
     return(QueryHelpers.AddQueryString(url, "id", GetTorrentId(tabNode)));
 }
Example #23
0
        public async Task <ActionResult> GetInstances(
            string org,
            string appId,
            [FromQuery(Name = "process.currentTask")] string currentTaskId,
            [FromQuery(Name = "process.isComplete")] bool?processIsComplete,
            [FromQuery(Name = "process.endEvent")] string processEndEvent,
            [FromQuery(Name = "process.ended")] string processEnded,
            [FromQuery(Name = "instanceOwner.partyId")] int?instanceOwnerPartyId,
            [FromQuery(Name = "appOwner.labels")] string labels,
            [FromQuery] string lastChanged,
            [FromQuery] string created,
            [FromQuery(Name = "visibleAfter")] string visibleAfter,
            [FromQuery] string dueBefore,
            string continuationToken,
            int?size)
        {
            int    pageSize = size ?? 100;
            string selfContinuationToken = null;

            if (!string.IsNullOrEmpty(continuationToken))
            {
                selfContinuationToken = continuationToken;
                continuationToken     = HttpUtility.UrlDecode(continuationToken);
            }

            Dictionary <string, StringValues> queryParams = QueryHelpers.ParseQuery(Request.QueryString.Value);

            string host  = $"{Request.Scheme}://{Request.Host.ToUriComponent()}";
            string url   = Request.Path;
            string query = Request.QueryString.Value;

            _logger.LogInformation($"uri = {url}{query}");

            try
            {
                InstanceQueryResponse result = await _instanceRepository.GetInstancesOfApplication(queryParams, continuationToken, pageSize);

                if (!string.IsNullOrEmpty(result.Exception))
                {
                    return(BadRequest(result.Exception));
                }

                string nextContinuationToken = HttpUtility.UrlEncode(result.ContinuationToken);
                result.ContinuationToken = null;

                QueryResponse <Instance> response = new QueryResponse <Instance>
                {
                    Instances = result.Instances,
                    Count     = result.Instances.Count,
                    TotalHits = result.TotalHits ?? 0
                };

                if (continuationToken == null)
                {
                    string selfUrl = $"{host}{url}{query}";
                    response.Self = selfUrl;
                }
                else
                {
                    string selfQueryString = BuildQueryStringWithOneReplacedParameter(
                        queryParams,
                        "continuationToken",
                        selfContinuationToken);

                    string selfUrl = $"{host}{url}{selfQueryString}";

                    response.Self = selfUrl;
                }

                if (nextContinuationToken != null)
                {
                    string nextQueryString = BuildQueryStringWithOneReplacedParameter(
                        queryParams,
                        "continuationToken",
                        nextContinuationToken);

                    string nextUrl = $"{host}{url}{nextQueryString}";

                    response.Next = nextUrl;
                }

                // add self links to platform
                result.Instances.ForEach(i => AddSelfLinks(Request, i));

                return(Ok(response));
            }
            catch (Exception e)
            {
                _logger.LogError($"Unable to perform query on instances due to: {e}");
                return(StatusCode(500, $"Unable to perform query on instances due to: {e.Message}"));
            }
        }
Example #24
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions <AuthenticationConfig> authConfig, ApplicationDbContext context)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseApplicationInsightsRequestTelemetry();

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            context.Database.Migrate();

            app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

            app.UseApplicationInsightsExceptionTelemetry();

            app.UseStaticFiles();

            app.UseIdentity();

            app.UseFacebookAuthentication(options =>
            {
                options.AppId     = authConfig.Value.Facebook.AppId;
                options.AppSecret = authConfig.Value.Facebook.AppSecret;
                options.Scope.Add("public_profile");
                options.Scope.Add("email");
                options.Events = new OAuthEvents
                {
                    OnCreatingTicket = ctx =>
                    {
                        var pic = ctx.User.SelectToken("picture.data.url").ToString();
                        ctx.Identity.AddClaim(new Claim("picture", pic));
                        return(Task.FromResult(0));
                    }
                };
                options.UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name,location,picture";
            });

            app.UseOAuthAuthentication(options =>
            {
                options.DisplayName             = "VK";
                options.AuthenticationScheme    = "VK";
                options.ClientId                = authConfig.Value.Vk.ClientId;
                options.ClientSecret            = authConfig.Value.Vk.ClientSecret;
                options.CallbackPath            = new PathString("/signin-vk");
                options.AuthorizationEndpoint   = "https://oauth.vk.com/authorize";
                options.TokenEndpoint           = "https://oauth.vk.com/access_token";
                options.UserInformationEndpoint = "https://api.vk.com/method/users.get";
                options.Scope.Add("email");
                options.Scope.Add("offline");
                options.Events = new OAuthEvents
                {
                    OnCreatingTicket = async ctx =>
                    {
                        var userId  = ctx.TokenResponse.Response.SelectToken("user_id").ToString();
                        var url     = QueryHelpers.AddQueryString(ctx.Options.UserInformationEndpoint, "user_id", userId);
                        url         = QueryHelpers.AddQueryString(url, "access_token", ctx.AccessToken);
                        url         = QueryHelpers.AddQueryString(url, "fields", "photo_50");
                        var request = new HttpRequestMessage(HttpMethod.Get, url);

                        var response = await ctx.Backchannel.SendAsync(request, ctx.HttpContext.RequestAborted);
                        response.EnsureSuccessStatusCode();

                        var user  = JObject.Parse(await response.Content.ReadAsStringAsync());
                        var email = ctx.TokenResponse.Response.SelectToken("email");

                        if (email != null)
                        {
                            ctx.Identity.AddClaim(new Claim(ClaimTypes.Email, email.ToString(), ClaimValueTypes.String, ctx.Options.ClaimsIssuer));
                        }

                        var fullName = user.SelectToken("response[0].first_name").Value <string>() + " " + user.SelectToken("response[0].last_name").Value <string>();
                        if (!string.IsNullOrEmpty(fullName))
                        {
                            ctx.Identity.AddClaim(new Claim(ClaimTypes.Name, fullName, ClaimValueTypes.String, ctx.Options.ClaimsIssuer));
                        }

                        var picture = user.SelectToken("response[0].photo_50").Value <string>();
                        if (!string.IsNullOrEmpty(picture))
                        {
                            ctx.Identity.AddClaim(new Claim("picture", picture, ClaimValueTypes.String, ctx.Options.ClaimsIssuer));
                        }

                        ctx.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId, ClaimValueTypes.String, ctx.Options.ClaimsIssuer));
                    }
                };
            });

            app.UseMvcWithDefaultRoute();
        }
 public static TParameters Parse(string queryString)
 {
     var nvc = QueryHelpers.ParseQuery(queryString);
     return Parse(nvc);
 }
Example #26
0
        public IActionResult ProjectMilestones(string listName = null, string entityName = null, int page = 0)
        {
            var response = new ResponseModel();

            #region << Can user read projects >>
            //Get current user
            ErpUser user = SecurityContext.CurrentUser;
            //Get entity meta
            var entity = entityManager.ReadEntity(entityName).Object;
            //Get list meta
            var list = entityManager.ReadRecordList(entity.Name, listName).Object;
            //check if user role has permissions
            var canRead   = user.Roles.Any(x => entity.RecordPermissions.CanRead.Any(z => z == x.Id));
            var canCreate = user.Roles.Any(x => entity.RecordPermissions.CanCreate.Any(z => z == x.Id));
            var canUpdate = user.Roles.Any(x => entity.RecordPermissions.CanUpdate.Any(z => z == x.Id));
            var canDelete = user.Roles.Any(x => entity.RecordPermissions.CanDelete.Any(z => z == x.Id));

            if (!canRead)
            {
                response.Success   = false;
                response.Message   = "You do not have permission to read the projects in this system";
                response.Timestamp = DateTime.UtcNow;
                return(Json(response));                //return empty object
            }
            #endregion

            #region << Get the project id >>
            var queryString   = HttpContext.Request.QueryString.ToString();
            var queryKeyValue = QueryHelpers.ParseQuery(queryString);
            var projectId     = new Guid();
            if (queryKeyValue.ContainsKey("recordId") && Guid.TryParse(queryKeyValue["recordId"], out projectId))
            {
            }
            else
            {
                response.Success   = false;
                response.Timestamp = DateTime.UtcNow;
                response.Message   = "Project Id either not found or not a GUID";
                response.Object    = null;
            }
            #endregion

            #region << Get milestone data >>
            var requestedFields = "id,name,start_date,end_date,x_tasks_not_started,x_tasks_in_progress,x_tasks_completed,x_bugs_opened,x_bugs_reopened,x_bugs_closed";

            QueryObject filterObj = EntityQuery.QueryEQ("project_id", projectId);

            var sortList = new List <QuerySortObject>();
            sortList.Add(new QuerySortObject("end_date", QuerySortType.Descending));
            EntityQuery resultQuery = new EntityQuery("wv_milestone", requestedFields, filterObj, sortList.ToArray(), null, null, null);

            QueryResponse result = recMan.Find(resultQuery);
            if (!result.Success)
            {
                response.Success   = false;
                response.Timestamp = DateTime.UtcNow;
                response.Message   = result.Message;
                response.Object    = null;
                return(Json(response));
            }
            #endregion
            var resultRecordsList = new List <EntityRecord>();
            foreach (var record in result.Object.Data)
            {
                var recordObj = new EntityRecord();
                recordObj["id"]         = record["id"];
                recordObj["name"]       = record["name"];
                recordObj["start_date"] = record["start_date"];
                recordObj["end_date"]   = record["end_date"];

                #region << tasks Count "not started" vs "in progress" vs "completed" >>
                var tasksNotStarted = (decimal)record["x_tasks_not_started"];
                var tasksInProgress = (decimal)record["x_tasks_in_progress"];
                var tasksCompleted  = (decimal)record["x_tasks_completed"];

                recordObj["tasks_not_started_count"] = tasksNotStarted;
                recordObj["tasks_in_progress_count"] = tasksInProgress;
                recordObj["tasks_completed_count"]   = tasksCompleted;
                if (tasksNotStarted + tasksInProgress + tasksCompleted > 0)
                {
                    recordObj["tasks_not_started_percentage"] = Math.Round((decimal)(tasksNotStarted * 100) / (tasksNotStarted + tasksInProgress + tasksCompleted));
                    recordObj["tasks_in_progress_percentage"] = Math.Round((decimal)(tasksInProgress * 100) / (tasksNotStarted + tasksInProgress + tasksCompleted));
                    recordObj["tasks_completed_percentage"]   = 100 - Math.Round((decimal)(tasksNotStarted * 100) / (tasksNotStarted + tasksInProgress + tasksCompleted)) - Math.Round((decimal)(tasksInProgress * 100) / (tasksNotStarted + tasksInProgress + tasksCompleted));
                }
                else
                {
                    recordObj["tasks_not_started_percentage"] = 0;
                    recordObj["tasks_in_progress_percentage"] = 0;
                    recordObj["tasks_completed_percentage"]   = 0;
                }
                #endregion

                #region << bugs Count "opened" & "reopened" vs "closed" >>
                var bugsOpened   = (decimal)record["x_bugs_opened"];
                var bugsReOpened = (decimal)record["x_bugs_reopened"];
                var bugsClosed   = (decimal)record["x_bugs_closed"];

                recordObj["bugs_opened_count"]   = bugsOpened;
                recordObj["bugs_reopened_count"] = bugsReOpened;
                recordObj["bugs_closed_count"]   = bugsClosed;
                if (bugsOpened + bugsReOpened + bugsClosed > 0)
                {
                    recordObj["bugs_opened_percentage"]   = Math.Round((decimal)(bugsOpened * 100) / (bugsOpened + bugsReOpened + bugsClosed));
                    recordObj["bugs_reopened_percentage"] = Math.Round((decimal)(bugsReOpened * 100) / (bugsOpened + bugsReOpened + bugsClosed));
                    recordObj["bugs_closed_percentage"]   = 100 - Math.Round((decimal)(bugsOpened * 100) / (bugsOpened + bugsReOpened + bugsClosed)) - Math.Round((decimal)(bugsReOpened * 100) / (bugsOpened + bugsReOpened + bugsClosed));
                }
                else
                {
                    recordObj["bugs_opened_percentage"]   = 0;
                    recordObj["bugs_reopened_percentage"] = 0;
                    recordObj["bugs_closed_percentage"]   = 0;
                }

                #endregion
                resultRecordsList.Add(recordObj);
            }

            response.Success   = true;
            response.Timestamp = DateTime.UtcNow;
            response.Message   = "My projects successfully read";
            response.Object    = resultRecordsList;

            return(Json(response));
        }
Example #27
0
 private string BuildRequestUri(string relativePath)
 {
     // combine /data/2.5/forecast/ with query params ?appid=...&lang=de
     return(QueryHelpers.AddQueryString(relativePath, this.CreateDefaultQueryParameters()));
 }
        protected override async Task <AuthenticationTicket> CreateTicketAsync(
            [NotNull] ClaimsIdentity identity,
            [NotNull] AuthenticationProperties properties,
            [NotNull] OAuthTokenResponse tokens)
        {
            var identifier = await GetUserIdentifierAsync(tokens);

            if (string.IsNullOrEmpty(identifier))
            {
                throw new HttpRequestException("An error occurred while retrieving the user identifier.");
            }

            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, identifier, ClaimValueTypes.String, Options.ClaimsIssuer));

            var address = QueryHelpers.AddQueryString(Options.UserInformationEndpoint, new Dictionary <string, string>
            {
                ["oauth_consumer_key"] = Options.ClientId,
                ["access_token"]       = tokens.AccessToken,
                ["openid"]             = identifier,
            });
            HttpResponseMessage response = null;

            try
            {
                response = await Backchannel.GetAsync(address);

                if (!response.IsSuccessStatusCode)
                {
                    Logger.LogError("An error occurred while retrieving the user profile: the remote server " +
                                    "returned a {Status} response with the following payload: {Headers} {Body}.",
                                    /* Status: */ response.StatusCode,
                                    /* Headers: */ response.Headers.ToString(),
                                    /* Body: */ await response.Content.ReadAsStringAsync());

                    throw new HttpRequestException("An error occurred while retrieving user information.");
                }

                var payload = JObject.Parse(await response.Content.ReadAsStringAsync());

                var status = payload.Value <int>("ret");
                if (status != 0)
                {
                    Logger.LogError("An error occurred while retrieving the user profile: the remote server " +
                                    "returned a {Status} response with the following message: {Message}.",
                                    /* Status: */ status,
                                    /* Message: */ payload.Value <string>("msg"));

                    throw new HttpRequestException("An error occurred while retrieving user information.");
                }

                var principal = new ClaimsPrincipal(identity);
                var context   = new OAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, payload);
                context.RunClaimActions(payload);

                await Options.Events.CreatingTicket(context);

                return(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name));
            }
            finally
            {
                response?.Dispose();
            }
        }
Example #29
0
        public ActionResult QQSignIn(string code)
        {
            try
            {
                /* 作者说明:续期功能未测试,有谁帮忙测一下。
                 */
                if (string.IsNullOrEmpty(code))
                {
                    return(Json(new { code = 1, Msg = "参数错误" }));
                }

                //QQ互联配置信息
                string appid = "101107448";
                string appkey = "ae7af6e66a8655f5dce06dce7fe20859";
                string status = "";
                string reurl = "https%3A%2F%2Fwww.bitadmincore.com%2Fauth%2Fqqsignin";
                string url, json;

                WebClient wcl = new WebClient();
                /*access_token有次数限制,不能每次都取一个新的,在有效期内可以使用,过了有效期则续期就可以了。*/
                if (string.IsNullOrEmpty(qq_access_token))
                {
                    url  = string.Format("https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id={0}&client_secret={1}&code={2}&state={3}&redirect_uri={4}", appid, appkey, code, status, reurl);
                    json = wcl.DownloadString(url);
                    //string token = "access_token=06B07A1CA3144B67BB8ECE03577E4DC5&expires_in=7776000&refresh_token=8DB41D424D74B1F79322946F0E3A17B0";
                    var param = QueryHelpers.ParseQuery(json);
                    qq_access_token  = param["access_token"];
                    qq_refresh_token = param["refresh_token"];
                    qq_expires_time  = DateTime.Now.AddSeconds(Convert.ToInt32(param["expires_in"].ToString()));
                }
                else if (qq_expires_time < DateTime.Now.AddMinutes(30))//提前30分钟续期
                {
                    url  = string.Format("https://graph.qq.com/oauth2.0/token?grant_type=refresh_token&client_id={0}&client_secret={1}&refresh_token={2}", appid, appkey, qq_refresh_token);
                    json = wcl.DownloadString(url);
                    //string token = "access_token=06B07A1CA3144B67BB8ECE03577E4DC5&expires_in=7776000&refresh_token=8DB41D424D74B1F79322946F0E3A17B0";
                    var param = QueryHelpers.ParseQuery(json);
                    qq_access_token  = param["access_token"];
                    qq_refresh_token = param["refresh_token"];
                    qq_expires_time  = DateTime.Now.AddSeconds(Convert.ToInt32(param["expires_in"].ToString()));
                }

                url  = "https://graph.qq.com/oauth2.0/me?access_token=" + qq_access_token;
                json = wcl.DownloadString(url);
                //json = "callback( {\"client_id\":\"101107448\",\"openid\":\"1B09CF38A9D917645272095DFF8B6074\"} );";
                var     mc        = new Regex("(?<=\\u0028).*?(?= \\u0029)", RegexOptions.None).Matches(json)[0];//提取出json对象
                JObject me        = JObject.Parse(mc.Value);
                string  client_id = (string)me["client_id"];
                string  openId    = (string)me["openid"];

                SysUserOpenId userOpenId = dbContext.Set <SysUserOpenId>().Where(x => x.OpenId == openId).FirstOrDefault();
                if (userOpenId != null && userOpenId.UserId != Guid.Empty)
                {
                    SSOClient.SignIn(userOpenId.UserId.Value);
                    return(Redirect("/pages/home/index.html"));
                }
                return(Redirect("/pages/account/bind.html?sign=pc&openid=" + openId));

                //自动创建本地用户,适用面向公众网站,项目根据需要调整逻辑。
                //url = string.Format("https://graph.qq.com/user/get_user_info?access_token={0}&oauth_consumer_key={1}&openid={2}", access_token, appid, openId);
                //wcl.Encoding = Encoding.UTF8;
                //json = wcl.DownloadString(url);
                //JObject qqUser = JObject.Parse(json.Replace("\\", ""));

                //var user = new SysUser();
                //user.UserId = Guid.NewGuid();
                //user.UserName = (string)qqUser["nickname"];//更多可用属性请查看官方接入文档
                //user.UserCode = Guid.NewGuid().ToString("N").Substring(20);
                //user.DepartmentId = new Guid("2379788E-45F0-417B-A103-0B6440A9D55D");
                //dbContext.SysUser.Add(user);

                //userOpenId = new SysUserOpenId();
                //userOpenId.OpenId = openId;
                //userOpenId.UserId = user.UserId;
                //userOpenId.CreateTime = DateTime.Now;
                //userOpenId.BindTime = DateTime.Now;
                //dbContext.SysUserOpenId.Add(userOpenId);

                //dbContext.SaveChanges();

                //SSOClient.SignIn(userOpenId.UserId.Value);
                //return Redirect("/pages/home/index.html");
            }
            catch (Exception ex)
            {
                LogHelper.SaveLog(ex);
                return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" }));
            }
        }
Example #30
0
        public ActionResult WeixinSignIn(string code)
        {
            try
            {
                /* 作者说明:因没有账号,本功能未测试。
                 *
                 * 作者疑问??
                 * 微信互联登录access_token逻辑感觉有问题:请求access_token时返回openid,那么access_token是跟appid绑定?还是跟openid绑定?
                 * 如果是跟openid绑定,那么需要维护一个access_token与openid关系及时效表,用户关闭应用重新启动登录时,只能重新获取code再获取openid,意义何在?
                 */

                if (string.IsNullOrEmpty(code))
                {
                    return(Json(new { code = 1, Msg = "参数错误" }));
                }

                //微信互联配置信息
                string appid = "";
                string appkey = "";
                string url, json, openid = string.Empty, unionid = string.Empty;//你要用openid还是用unionid请详读官网说明。

                WebClient wcl = new WebClient();

                /*access_token有次数限制,不能每次都取一个新的,在有效期内可以使用,过了有效期则续期就可以了。*/
                if (string.IsNullOrEmpty(weixin_access_token))
                {
                    url  = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, appkey, code);
                    json = wcl.DownloadString(url);
                    JObject weixinToken = JObject.Parse(json.Replace("\\", ""));
                    openid  = (string)weixinToken["openid"];//更多可用属性请查看官方接入文档(access_token,expires_in,refresh_token,openid,scope,unionid)
                    unionid = (string)weixinToken["unionid"];

                    weixin_access_token  = (string)weixinToken["access_token"];
                    weixin_refresh_token = (string)weixinToken["refresh_token"];
                    weixin_expires_time  = DateTime.Now.AddSeconds(Convert.ToInt32(weixinToken["expires_in"].ToString()));
                }
                else if (weixin_expires_time < DateTime.Now.AddMinutes(30))//提前30分钟续期
                {
                    url  = string.Format("https://api.weixin.qq.com/sns/oauth2/refresh_token?grant_type=refresh_token&appid={0}&refresh_token={1}", appid, weixin_refresh_token);
                    json = wcl.DownloadString(url);
                    //string token = "access_token=06B07A1CA3144B67BB8ECE03577E4DC5&expires_in=7776000&refresh_token=8DB41D424D74B1F79322946F0E3A17B0";
                    var param = QueryHelpers.ParseQuery(json);
                    weixin_access_token  = param["access_token"];
                    weixin_refresh_token = param["refresh_token"];
                    weixin_expires_time  = DateTime.Now.AddSeconds(Convert.ToInt32(param["expires_in"].ToString()));
                }

                SysUserOpenId userOpenId = dbContext.Set <SysUserOpenId>().Where(x => x.OpenId == openid).FirstOrDefault();
                if (userOpenId != null && userOpenId.UserId != Guid.Empty)
                {
                    SSOClient.SignIn(userOpenId.UserId.Value);
                    return(Redirect("/pages/home/index.html"));
                }
                return(Redirect("/pages/account/bind.html?sign=pc&openid=" + openid));

                //自动创建本地用户,适用面向公众网站,项目根据需要调整逻辑。
                //url = string.Format("https://api.weixin.qq.com//sns/userinfo?access_token={0}&openid={1}", weixin_access_token, appid, openid);
                //wcl.Encoding = Encoding.UTF8;
                //json = wcl.DownloadString(url);
                //JObject weixinUser = JObject.Parse(json.Replace("\\", ""));

                //var user = new SysUser();
                //user.UserId = Guid.NewGuid();
                //user.UserName = (string)weixinUser["nickname"];//更多可用属性请查看官方接入文档(openid,nickname,sex,province,city,country,headimgurl,privilege[],unionid)
                //user.UserCode = Guid.NewGuid().ToString("N").Substring(20);
                //user.DepartmentId = new Guid("2379788E-45F0-417B-A103-0B6440A9D55D");
                //dbContext.SysUser.Add(user);

                //userOpenId = new SysUserOpenId();
                //userOpenId.OpenId = openid;
                //userOpenId.UserId = user.UserId;
                //userOpenId.CreateTime = DateTime.Now;
                //userOpenId.BindTime = DateTime.Now;
                //dbContext.SysUserOpenId.Add(userOpenId);

                //dbContext.SaveChanges();

                //SSOClient.SignIn(userOpenId.UserId.Value);
                //return Redirect("/pages/home/index.html");
            }
            catch (Exception ex)
            {
                LogHelper.SaveLog(ex);
                return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" }));
            }
        }