Exemple #1
0
        public async Task AllowsEmptyHost(bool allowed, int status)
        {
            var builder = new WebHostBuilder()
                          .ConfigureServices(services =>
            {
                services.AddHostFiltering(options =>
                {
                    options.AllowEmptyHosts = allowed;
                    options.AllowedHosts.Add("Localhost");
                });
            })
                          .Configure(app =>
            {
                app.Use((ctx, next) =>
                {
                    ctx.Request.Headers[HeaderNames.Host] = " ";
                    return(next());
                });
                app.UseHostFiltering();
                app.Run(c =>
                {
                    Assert.True(c.Request.Headers.TryGetValue(HeaderNames.Host, out var host));
                    Assert.True(StringValues.Equals(" ", host));
                    return(Task.CompletedTask);
                });
                app.Run(c => Task.CompletedTask);
            });
            var server   = new TestServer(builder);
            var response = await server.CreateClient().GetAsync("/");

            Assert.Equal(status, (int)response.StatusCode);
        }
        public Task <VerifyGatewayResult> VerifyGateway(VerifyGatewayRequest request, PaymentGatewayRequest gatewayRequest, IFormCollection form)
        {
            if (form == null)
            {
                return(Task.FromResult(VerifyGatewayResult.Failed("Form verisi alınamadı.")));
            }

            string mdStatus = form["mdstatus"].ToString();

            if (string.IsNullOrEmpty(mdStatus))
            {
                return(Task.FromResult(VerifyGatewayResult.Failed(form["mderrormessage"], form["procreturncode"])));
            }

            StringValues response = form["response"];

            //mdstatus 1,2,3 veya 4 olursa 3D doğrulama geçildi anlamına geliyor
            if (!mdStatusCodes.Contains(mdStatus))
            {
                return(Task.FromResult(VerifyGatewayResult.Failed($"{response} - {form["mderrormessage"]}", form["procreturncode"])));
            }

            if (StringValues.IsNullOrEmpty(response) || !response.Equals("Approved"))
            {
                return(Task.FromResult(VerifyGatewayResult.Failed($"{response} - {form["errmsg"]}", form["procreturncode"])));
            }

            int.TryParse(form["txninstallmentcount"], out int installment);

            return(Task.FromResult(VerifyGatewayResult.Successed(form["transid"], form["hostrefnum"],
                                                                 installment, 0, response,
                                                                 form["procreturncode"], form["campaignchooselink"])));
        }
Exemple #3
0
        public IActionResult Negotiate(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequest req,
            [SignalRConnectionInfo(HubName = "events")] SignalRConnectionInfo connectionInfo)
        {
            var expectedKey = Environment.GetEnvironmentVariable("AccessKey");

            if (string.IsNullOrEmpty(expectedKey))
            {
                return(new OkObjectResult(connectionInfo));
            }

            var accessKey = req.Query["accessKey"];

            if (StringValues.IsNullOrEmpty(accessKey))
            {
                accessKey = req.Query["key"];
            }
            if (StringValues.IsNullOrEmpty(accessKey))
            {
                accessKey = req.Query["k"];
            }

            if (StringValues.IsNullOrEmpty(accessKey) ||
                !StringValues.Equals(expectedKey, accessKey))
            {
                return(new UnauthorizedResult());
            }

            return(new OkObjectResult(connectionInfo));
        }
Exemple #4
0
    protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync()
    {
        // Taken from the base class' implementation so we can modify the status code check
        // for "access denied" as LinkedIn uses non-standard error codes (see https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers/issues/480).
        // https://github.com/dotnet/aspnetcore/blob/bbf7c8780c42e3d32aeec8018367037784eb9181/src/Security/Authentication/OAuth/src/OAuthHandler.cs#L49-L87
        var query = Request.Query;

        var state      = query["state"];
        var properties = Options.StateDataFormat.Unprotect(state);

        if (properties == null)
        {
            return(HandleRequestResult.Fail("The oauth state was missing or invalid."));
        }

        // OAuth2 10.12 CSRF
        if (!ValidateCorrelationId(properties))
        {
            return(HandleRequestResult.Fail("Correlation failed.", properties));
        }

        var error = query["error"];

        if (!StringValues.IsNullOrEmpty(error))
        {
            // Note: access_denied errors are special protocol errors indicating the user didn't
            // approve the authorization demand requested by the remote authorization server.
            // Since it's a frequent scenario (that is not caused by incorrect configuration),
            // denied errors are handled differently using HandleAccessDeniedErrorAsync().
            // Visit https://tools.ietf.org/html/rfc6749#section-4.1.2.1 for more information.
            var errorDescription = query["error_description"];
            var errorUri         = query["error_uri"];

            // See https://docs.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow#application-is-rejected
            if (StringValues.Equals(error, "access_denied") ||
                StringValues.Equals(error, "user_cancelled_login") ||
                StringValues.Equals(error, "user_cancelled_authorize"))
            {
                var result = await HandleAccessDeniedErrorAsync(properties);

                if (!result.None)
                {
                    return(result);
                }

                var deniedEx = new Exception("Access was denied by the resource owner or by the remote server.");
                deniedEx.Data["error"]             = error.ToString();
                deniedEx.Data["error_description"] = errorDescription.ToString();
                deniedEx.Data["error_uri"]         = errorUri.ToString();

                return(HandleRequestResult.Fail(deniedEx, properties));
            }
        }

        return(await base.HandleRemoteAuthenticateAsync());
    }
 /// <summary>
 /// Returns a value indicating whether the specified object occurs within this collection.
 /// </summary>
 /// <param name="item">The item.</param>
 /// <returns>true if the specified object occurs within this collection; otherwise, false.</returns>
 public bool Contains(KeyValuePair <string, StringValues> item)
 {
     if (Store == null ||
         !Store.TryGetValue(item.Key, out StringValues value) ||
         !StringValues.Equals(value, item.Value))
     {
         return(false);
     }
     return(true);
 }
        /// <summary>
        /// Removes the given item from the the collection.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns>true if the specified object was removed from the collection; otherwise, false.</returns>
        public bool Remove(KeyValuePair <string, StringValues> item)
        {
            ThrowIfReadOnly();
            if (Store == null)
            {
                return(false);
            }

            if (Store.TryGetValue(item.Key, out var value) && StringValues.Equals(item.Value, value))
            {
                return(Store.Remove(item.Key));
            }
            return(false);
        }
Exemple #7
0
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj))
            {
                return(true);
            }

            if (obj is null || GetType() != obj.GetType())
            {
                return(false);
            }

            var other = (QueryableHandlerExpression)obj;

            return(_queryableHandler == other._queryableHandler && _parameterValue.Equals(other._parameterValue));
        }
        /// <summary>
        /// Handles the request made by the event grid to validate the subscriber end point
        /// is ready to handle calls from the event grid for publishing events.
        /// </summary>
        /// <param name="requestBody">The string value of the request body.</param>
        /// <param name="headers">The headers of the request.</param>
        /// <returns>IActionResult.</returns>
        public IActionResult HandleSubscriptionValidationEvent(string requestBody, StringValues headers)
        {
            dynamic data = JsonConvert.DeserializeObject(requestBody);

            foreach (var dataEvent in data)
            {
                if (headers.Equals("SubscriptionValidation") &&
                    dataEvent.eventType == "Microsoft.EventGrid.SubscriptionValidationEvent")
                {
                    // this is a special event type that needs an echo response for Event Grid to work
                    var validationCode = dataEvent.data.validationCode; // TODO .ToString();
                    var echoResponse   = new { validationResponse = validationCode };
                    return(new OkObjectResult(echoResponse));
                }
            }

            return(null);
        }
        /// <summary>
        /// Finalize cache headers.
        /// </summary>
        /// <param name="context"></param>
        /// <returns><c>true</c> if a vary by entry needs to be stored in the cache; otherwise <c>false</c>.</returns>
        private bool OnFinalizeCacheHeaders(ResponseCachingContext context)
        {
            if (_policyProvider.IsResponseCacheable(context))
            {
                var storeVaryByEntry = false;
                context.ShouldCacheResponse = true;

                // Create the cache entry now
                var response      = context.HttpContext.Response;
                var headers       = response.Headers;
                var varyHeaders   = new StringValues(headers.GetCommaSeparatedValues(HeaderNames.Vary));
                var varyQueryKeys = new StringValues(context.HttpContext.Features.Get <IResponseCachingFeature>()?.VaryByQueryKeys);
                context.CachedResponseValidFor = context.ResponseSharedMaxAge ??
                                                 context.ResponseMaxAge ??
                                                 (context.ResponseExpires - context.ResponseTime !.Value) ??
                                                 DefaultExpirationTimeSpan;

                // Generate a base key if none exist
                if (string.IsNullOrEmpty(context.BaseKey))
                {
                    context.BaseKey = _keyProvider.CreateBaseKey(context);
                }

                // Check if any vary rules exist
                if (!StringValues.IsNullOrEmpty(varyHeaders) || !StringValues.IsNullOrEmpty(varyQueryKeys))
                {
                    // Normalize order and casing of vary by rules
                    var normalizedVaryHeaders   = GetOrderCasingNormalizedStringValues(varyHeaders);
                    var normalizedVaryQueryKeys = GetOrderCasingNormalizedStringValues(varyQueryKeys);

                    // Update vary rules if they are different
                    if (context.CachedVaryByRules == null ||
                        !StringValues.Equals(context.CachedVaryByRules.QueryKeys, normalizedVaryQueryKeys) ||
                        !StringValues.Equals(context.CachedVaryByRules.Headers, normalizedVaryHeaders))
                    {
                        context.CachedVaryByRules = new CachedVaryByRules
                        {
                            VaryByKeyPrefix = FastGuid.NewGuid().IdString,
                            Headers         = normalizedVaryHeaders,
                            QueryKeys       = normalizedVaryQueryKeys
                        };
                    }

                    // Always overwrite the CachedVaryByRules to update the expiry information
                    _logger.VaryByRulesUpdated(normalizedVaryHeaders, normalizedVaryQueryKeys);
                    storeVaryByEntry = true;

                    context.StorageVaryKey = _keyProvider.CreateStorageVaryByKey(context);
                }

                // Ensure date header is set
                if (!context.ResponseDate.HasValue)
                {
                    context.ResponseDate = context.ResponseTime !.Value;
                    // Setting the date on the raw response headers.
                    headers.Date = HeaderUtilities.FormatDate(context.ResponseDate.Value);
                }

                // Store the response on the state
                context.CachedResponse = new CachedResponse
                {
                    Created    = context.ResponseDate.Value,
                    StatusCode = response.StatusCode,
                    Headers    = new HeaderDictionary()
                };

                foreach (var header in headers)
                {
                    if (!string.Equals(header.Key, HeaderNames.Age, StringComparison.OrdinalIgnoreCase))
                    {
                        context.CachedResponse.Headers[header.Key] = header.Value;
                    }
                }

                return(storeVaryByEntry);
            }

            context.ResponseCachingStream.DisableBuffering();
            return(false);
        }
Exemple #10
0
        protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync()
        {
            var query = Request.Query;

            var state      = query["state"];
            var properties = Options.StateDataFormat.Unprotect(state);

            if (properties == null)
            {
                return(HandleRequestResult.Fail("The oauth state was missing or invalid."));
            }

            // OAuth2 10.12 CSRF
            if (!ValidateCorrelationId(properties))
            {
                return(HandleRequestResult.Fail("Correlation failed.", properties));
            }

            var error = query["error"];

            if (!StringValues.IsNullOrEmpty(error))
            {
                // Note: access_denied errors are special protocol errors indicating the user didn't
                // approve the authorization demand requested by the remote authorization server.
                // Since it's a frequent scenario (that is not caused by incorrect configuration),
                // denied errors are handled differently using HandleAccessDeniedErrorAsync().
                // Visit https://tools.ietf.org/html/rfc6749#section-4.1.2.1 for more information.
                if (StringValues.Equals(error, "access_denied"))
                {
                    var result = await HandleAccessDeniedErrorAsync(properties);

                    return(!result.None ? result
                        : HandleRequestResult.Fail("Access was denied by the resource owner or by the remote server.", properties));
                }

                var failureMessage = new StringBuilder();
                failureMessage.Append(error);
                var errorDescription = query["error_description"];
                if (!StringValues.IsNullOrEmpty(errorDescription))
                {
                    failureMessage.Append(";Description=").Append(errorDescription);
                }
                var errorUri = query["error_uri"];
                if (!StringValues.IsNullOrEmpty(errorUri))
                {
                    failureMessage.Append(";Uri=").Append(errorUri);
                }

                return(HandleRequestResult.Fail(failureMessage.ToString(), properties));
            }

            var code = query["code"];

            if (StringValues.IsNullOrEmpty(code))
            {
                return(HandleRequestResult.Fail("Code was not found.", properties));
            }

            using (var tokens = await ExchangeCodeAsync(code, BuildRedirectUri(Options.CallbackPath), properties))
            {
                if (tokens.Error != null)
                {
                    return(HandleRequestResult.Fail(tokens.Error, properties));
                }

                if (string.IsNullOrEmpty(tokens.AccessToken))
                {
                    return(HandleRequestResult.Fail("Failed to retrieve access token.", properties));
                }

                var identity = new ClaimsIdentity(ClaimsIssuer);

                if (Options.SaveTokens)
                {
                    var authTokens = new List <AuthenticationToken>();

                    authTokens.Add(new AuthenticationToken {
                        Name = "access_token", Value = tokens.AccessToken
                    });
                    if (!string.IsNullOrEmpty(tokens.RefreshToken))
                    {
                        authTokens.Add(new AuthenticationToken {
                            Name = "refresh_token", Value = tokens.RefreshToken
                        });
                    }

                    if (!string.IsNullOrEmpty(tokens.TokenType))
                    {
                        authTokens.Add(new AuthenticationToken {
                            Name = "token_type", Value = tokens.TokenType
                        });
                    }

                    if (!string.IsNullOrEmpty(tokens.ExpiresIn))
                    {
                        int value;
                        if (int.TryParse(tokens.ExpiresIn, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
                        {
                            // https://www.w3.org/TR/xmlschema-2/#dateTime
                            // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
                            var expiresAt = Clock.UtcNow + TimeSpan.FromSeconds(value);
                            authTokens.Add(new AuthenticationToken
                            {
                                Name  = "expires_at",
                                Value = expiresAt.ToString("o", CultureInfo.InvariantCulture)
                            });
                        }
                    }

                    properties.StoreTokens(authTokens);
                }

                var ticket = await CreateTicketAsync(identity, properties, tokens);

                if (ticket != null)
                {
                    return(HandleRequestResult.Success(ticket));
                }
                else
                {
                    return(HandleRequestResult.Fail("Failed to retrieve user information from remote server.", properties));
                }
            }
        }
        private async Task <HandleRequestResult> HandleRemoteAuthenticateAsync(
            [NotNull] Dictionary <string, StringValues> parameters)
        {
            // Adapted from https://github.com/aspnet/AspNetCore/blob/66de493473521e173fa15ca557f5f97601cedb23/src/Security/Authentication/OAuth/src/OAuthHandler.cs#L48-L175
            if (!parameters.TryGetValue("state", out var state))
            {
                state = default;
            }

            var properties = Options.StateDataFormat.Unprotect(state);

            if (properties == null)
            {
                return(HandleRequestResult.Fail("The oauth state was missing or invalid."));
            }

            // OAuth2 10.12 CSRF
            if (!ValidateCorrelationId(properties))
            {
                return(HandleRequestResult.Fail("Correlation failed.", properties));
            }

            if (!parameters.TryGetValue("error", out var error))
            {
                error = default;
            }

            if (!StringValues.IsNullOrEmpty(error))
            {
                // Note: access_denied errors are special protocol errors indicating the user didn't
                // approve the authorization demand requested by the remote authorization server.
                // Since it's a frequent scenario (that is not caused by incorrect configuration),
                // denied errors are handled differently using HandleAccessDeniedErrorAsync().
                // Visit https://tools.ietf.org/html/rfc6749#section-4.1.2.1 for more information.
                if (!parameters.TryGetValue("error_description", out var errorDescription))
                {
                    errorDescription = default;
                }

                if (!parameters.TryGetValue("error_uri", out var errorUri))
                {
                    errorUri = default;
                }

                // See https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_js/incorporating_sign_in_with_apple_into_other_platforms.
                if (StringValues.Equals(error, "access_denied") || StringValues.Equals(error, "user_cancelled_authorize"))
                {
                    var result = await HandleAccessDeniedErrorAsync(properties);

                    if (!result.None)
                    {
                        return(result);
                    }

                    var deniedEx = new Exception("Access was denied by the resource owner or by the remote server.");

                    deniedEx.Data["error"]             = error.ToString();
                    deniedEx.Data["error_description"] = errorDescription.ToString();
                    deniedEx.Data["error_uri"]         = errorUri.ToString();

                    return(HandleRequestResult.Fail(deniedEx, properties));
                }

                var failureMessage = new StringBuilder().Append(error);

                if (!StringValues.IsNullOrEmpty(errorDescription))
                {
                    failureMessage.Append(";Description=").Append(errorDescription);
                }

                if (!StringValues.IsNullOrEmpty(errorUri))
                {
                    failureMessage.Append(";Uri=").Append(errorUri);
                }

                var ex = new Exception(failureMessage.ToString());

                ex.Data["error"]             = error.ToString();
                ex.Data["error_description"] = errorDescription.ToString();
                ex.Data["error_uri"]         = errorUri.ToString();

                return(HandleRequestResult.Fail(ex, properties));
            }

            if (!parameters.TryGetValue("code", out var code))
            {
                code = default;
            }

            if (StringValues.IsNullOrEmpty(code))
            {
                return(HandleRequestResult.Fail("Code was not found.", properties));
            }

            var codeExchangeContext = new OAuthCodeExchangeContext(properties, code, BuildRedirectUri(Options.CallbackPath));

            using var tokens = await ExchangeCodeAsync(codeExchangeContext);

            if (tokens.Error != null)
            {
                return(HandleRequestResult.Fail(tokens.Error, properties));
            }

            if (string.IsNullOrEmpty(tokens.AccessToken))
            {
                return(HandleRequestResult.Fail("Failed to retrieve access token.", properties));
            }

            var identity = new ClaimsIdentity(ClaimsIssuer);

            if (Options.SaveTokens)
            {
                var authTokens = new List <AuthenticationToken>()
                {
                    new AuthenticationToken()
                    {
                        Name = "access_token", Value = tokens.AccessToken
                    },
                };

                if (!string.IsNullOrEmpty(tokens.RefreshToken))
                {
                    authTokens.Add(new AuthenticationToken()
                    {
                        Name = "refresh_token", Value = tokens.RefreshToken
                    });
                }

                if (!string.IsNullOrEmpty(tokens.TokenType))
                {
                    authTokens.Add(new AuthenticationToken()
                    {
                        Name = "token_type", Value = tokens.TokenType
                    });
                }

                if (!string.IsNullOrEmpty(tokens.ExpiresIn))
                {
                    if (int.TryParse(tokens.ExpiresIn, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value))
                    {
                        // https://www.w3.org/TR/xmlschema-2/#dateTime
                        // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
                        var expiresAt = Clock.UtcNow + TimeSpan.FromSeconds(value);

                        authTokens.Add(new AuthenticationToken()
                        {
                            Name  = "expires_at",
                            Value = expiresAt.ToString("o", CultureInfo.InvariantCulture),
                        });
                    }
                }

                properties.StoreTokens(authTokens);
            }

            if (parameters.TryGetValue("user", out var userJson))
            {
                using var user = JsonDocument.Parse(userJson);
                var userClaims = ExtractClaimsFromUser(user.RootElement);

                foreach (var claim in userClaims)
                {
                    identity.AddClaim(claim);
                }
            }

            var ticket = await CreateTicketAsync(identity, properties, tokens);

            if (ticket != null)
            {
                return(HandleRequestResult.Success(ticket));
            }
            else
            {
                return(HandleRequestResult.Fail("Failed to retrieve user information from remote server.", properties));
            }
        }
Exemple #12
0
 public bool Equals(HeaderSegmentCollection other)
 {
     return(StringValues.Equals(_headers, other._headers));
 }
        public void Equals_Instance()
        {
            var equalString = "abc";

            var equalStringArray = new string[] { equalString };
            var equalStringValues = new StringValues(equalString);
            var stringArray = new string[] { equalString, equalString };
            var stringValuesArray = new StringValues(stringArray);

            Assert.True(equalStringValues.Equals(equalStringValues));
            Assert.True(equalStringValues.Equals(equalString));
            Assert.True(equalStringValues.Equals(equalStringArray));
            Assert.True(stringValuesArray.Equals(stringArray));
        }