Ejemplo n.º 1
0
        public static CorsResult EvaluatePolicy(NancyContext context, string policyName)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var request = context.Request;
            var policy  = _options.GetPolicy(policyName);

            return(EvaluatePolicy(request, policy));
        }
        /// <summary>
        /// Handle unhandled exceptions
        /// </summary>
        /// <param name="context">Current HttpContext</param>
        /// <param name="exception">System.Exception.</param>
        private async Task HandleUnhandledExceptionAsync(HttpContext context, Exception exception)
        {
            _logger.LogError(exception, exception.Message);

            if (!context.Response.HasStarted)
            {
                context.Response.Clear();

                //repopulate Response header with CORS policy to send the response with CORS headers
                _corsService.ApplyResult(_corsService.EvaluatePolicy(context, _corsOptions.GetPolicy("Default")),
                                         context.Response);

                context.Response.ContentType = "application/json";
                context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;

                var message = string.Empty;
                if (_settings.DetailedErrors)
                {
                    message = exception.Message;
                }
                else
                {
                    message = "An unhandled exception has occurred.";
                }

                //implement unified error messaging approach
                var result = new ExceptionMessage(message).ToString();
                await context.Response.WriteAsync(result);
            }
        }
        public void Create_ReturnsCorsOptions(CorsOptions options)
        {
            var action = CorsOptionsFactory.Create();

            action.Invoke(options);

            // Asserts
            options.GetPolicy("CorsPolicy").Should().NotBeNull();
        }
Ejemplo n.º 4
0
        public static CorsResult EvaluatePolicy(HttpContextBase context, string policyName)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var policy = _options.GetPolicy(policyName);

            return(EvaluatePolicy(context, policy));
        }
Ejemplo n.º 5
0
        public async Task <CorsResult> EvaluatePolicy(HttpContext context, string policyName)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var policy = _options.GetPolicy(policyName);

            return(await EvaluatePolicy(context, policy));
        }
        /// <summary>
        /// Handle HTTP exceptions
        /// </summary>
        /// <param name="context">Current HttpContext.</param>
        /// <param name="exception">Custom HTTP exception.</param>
        private async Task HandleHttpExceptionAsync(HttpContext context, HttpException exception)
        {
            _logger.LogError(exception, exception.MessageDetail ?? exception.Message);

            if (!context.Response.HasStarted)
            {
                int    statusCode = exception.StatusCode;
                string message    = exception.Message;

                context.Response.Clear();

                //repopulate Response header with CORS policy
                _corsService.ApplyResult(_corsService.EvaluatePolicy(context, _corsOptions.GetPolicy("Default")), context.Response);

                context.Response.ContentType = "application/json";
                context.Response.StatusCode  = statusCode;

                var result = new ExceptionMessage(message).ToString();
                await context.Response.WriteAsync(result);
            }
        }
Ejemplo n.º 7
0
    public void AddDefaultPolicy_OverridesDefaultPolicyName()
    {
        // Arrange
        var corsOptions    = new CorsOptions();
        var expectedPolicy = new CorsPolicy();

        // Act
        corsOptions.AddDefaultPolicy(new CorsPolicy());
        corsOptions.AddDefaultPolicy(expectedPolicy);

        // Assert
        var actualPolicy = corsOptions.GetPolicy(corsOptions.DefaultPolicyName);

        Assert.Same(expectedPolicy, actualPolicy);
    }
Ejemplo n.º 8
0
    /// <summary>
    /// Looks up a policy using the <paramref name="policyName"/> and then evaluates the policy using the passed in
    /// <paramref name="context"/>.
    /// </summary>
    /// <param name="context"></param>
    /// <param name="policyName"></param>
    /// <returns>A <see cref="CorsResult"/> which contains the result of policy evaluation and can be
    /// used by the caller to set appropriate response headers.</returns>
    public CorsResult EvaluatePolicy(HttpContext context, string policyName)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        var policy = _options.GetPolicy(policyName);

        if (policy is null)
        {
            throw new InvalidOperationException(Resources.FormatPolicyNotFound(policyName));
        }

        return(EvaluatePolicy(context, policy));
    }
        public Task <CorsPolicy> GetPolicyAsync(HttpContext context, string policyName)
        {
            var originHeader = context.Request.Headers["Origin"].FirstOrDefault();

            // unknown policy name or origin header not present: default behavior
            if (string.IsNullOrEmpty(policyName) ||
                string.IsNullOrEmpty(originHeader) ||
                !string.Equals(policyName, DefaultSenseNetCorsPolicyName, StringComparison.InvariantCultureIgnoreCase) ||
                string.Equals(originHeader, "null", StringComparison.InvariantCultureIgnoreCase))
            {
                return(Task.FromResult(_options.GetPolicy(policyName ?? _options.DefaultPolicyName)));
            }

            var policyBuilder = new CorsPolicyBuilder();

            // Load current CORS settings from the repository. This must not be cached here,
            // because settings may change at runtime, anytime.
            var corsSettings =
                Settings.GetValue <IEnumerable <string> >(PortalSettings.SETTINGSNAME,
                                                          PortalSettings.SETTINGS_ALLOWEDORIGINDOMAINS, null,
                                                          SnCorsConstants.DefaultAllowedDomains);

            // get a configured domain (or template) that matches the origin sent by the client
            var allowedDomain = GetAllowedDomain(originHeader, corsSettings);

            if (!string.IsNullOrEmpty(allowedDomain))
            {
                // template match: set the allowed origin
                policyBuilder.WithOrigins(originHeader);

                // any origin ('*') and credentials are mutually exclusive
                if (!string.Equals(originHeader, CorsConstants.AnyOrigin))
                {
                    policyBuilder.AllowCredentials();
                }

                var allowedMethods = Settings.GetValue(PortalSettings.SETTINGSNAME, PortalSettings.SETTINGS_ALLOWEDMETHODS, null,
                                                       SnCorsConstants.AccessControlAllowMethodsDefault);
                var allowedHeaders = Settings.GetValue(PortalSettings.SETTINGSNAME, PortalSettings.SETTINGS_ALLOWEDHEADERS, null,
                                                       SnCorsConstants.AccessControlAllowHeadersDefault);

                policyBuilder.WithMethods(allowedMethods);
                policyBuilder.WithHeaders(allowedHeaders);
            }

            return(Task.FromResult(policyBuilder.Build()));
        }
Ejemplo n.º 10
0
    public void AddDefaultPolicy_UsingPolicyBuilder_SetsDefaultPolicyName()
    {
        // Arrange
        var        corsOptions    = new CorsOptions();
        CorsPolicy expectedPolicy = null;

        // Act
        corsOptions.AddPolicy("policy1", policyBuilder =>
        {
            policyBuilder.AllowAnyOrigin().Build();
        });
        corsOptions.AddDefaultPolicy(policyBuilder =>
        {
            expectedPolicy = policyBuilder.AllowAnyOrigin().Build();
        });
        corsOptions.AddPolicy("policy3", new CorsPolicy());

        // Assert
        var actualPolicy = corsOptions.GetPolicy(corsOptions.DefaultPolicyName);

        Assert.Same(expectedPolicy, actualPolicy);
    }
Ejemplo n.º 11
0
 public CorsPolicy GetPolicy()
 {
     return(_options.GetPolicy(_options.DefaultPolicyName));
 }
Ejemplo n.º 12
0
 public Task <CorsPolicy> GetPolicyAsync(HttpContext context, string policyName)
 {
     // if no EnableCors, it still comes to this function with empty policyName
     return(Task.FromResult(_options.GetPolicy(policyName ?? _options.DefaultPolicyName)));
 }
 public CorsPolicy GetPolicy()
 {
     return(_options.GetPolicy(CorsPoliciesEnums.DynamicCorsPolicyName));
 }