简体   繁体   中英

Definition of CORS Policy for sub domains in Asp.net Web API

I have a asp.net web api application. This application sends xhr requests to a web api backend which residents in another web server. For cross domain request issue I have enabled CORS option for web api. It works well with specified URLs.

 [EnableCors(origins: @"http://sub.company.com", headers: "*", methods: "get,post")]

It works from sub.company.com , but, it doesn't work for a subdomain of a subdomain that I specified like s1.sub.company.com . I appended that subdomain to the policy also but again not worked;

[EnableCors(origins: @"http://sub.company.com, http://s1.sub.company.com", headers: "*", methods: "get,post")]

How can I fix this problem?

You can create a custom CORS policy to do this. This will allow cross-domain access if the root domain are identical.

/// <summary> 
/// Cors policy provider that will allow cross-domain access if the request and the referrer has same root domain.
/// This also support credential headers and cookies.
/// See http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors
/// </summary>
public class IdenticalRootDomainCorsPolicyProvider : ICorsPolicyProvider
{
    private readonly string[] exposedHeaders;

    /// <summary> Details information when a cross-domain fails. </summary>
    public class CorsPolicyErrorDetails
    {
        /// <summary> The address from where request origins. </summary>
        public Uri Referrer { get; set; }

        /// <summary> The request URI. </summary>
        public Uri Request { get; set; }

        /// <summary> Specific message for the error. </summary>
        public string Message { get; set; }
    }

    /// <summary> Occurs when cross-domain access was not accepted. </summary>
    public event Action<CorsPolicyErrorDetails> CorsPolicyError;

    /// <summary> Initializes a new instance of the <see cref="IdenticalRootDomainCorsPolicyProvider"/> class. </summary>
    /// <param name="exposedHeaders"> Provide a list of header names that should be exposed. </param>
    public IdenticalRootDomainCorsPolicyProvider(params string[] exposedHeaders)
    {
        this.exposedHeaders = exposedHeaders;
    }

    /// <summary> Gets the <see cref="T:System.Web.Cors.CorsPolicy" />. </summary>
    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var origin = request.Headers.Where(x => x.Key == "Origin").Select(x => x.Value.FirstOrDefault()).FirstOrDefault();

        if (origin == null)
        {
            CorsPolicyError?.Invoke(new CorsPolicyErrorDetails { Message = "Could not find Origin in headers.", Request = request.RequestUri });
            return Task.FromResult((CorsPolicy)null);
        }

        var referrer = new Uri(origin);
        var referrerRootDomain = referrer.GetRootDomain();
        var requestRootDomain = request.RequestUri.GetRootDomain();

        var policy = new CorsPolicy();
        policy.AllowAnyHeader = true;
        policy.AllowAnyMethod = true;
        policy.SupportsCredentials = true;

        if (referrerRootDomain != requestRootDomain)
        {
            CorsPolicyError?.Invoke(new CorsPolicyErrorDetails { Referrer = referrer, Request = request.RequestUri });
            return Task.FromResult(policy);
        }

        // Standard ports which browser disregards should be handled (80, 443).
        if (referrer.Port == 80 || referrer.Scheme.Equals("https", StringComparison.InvariantCultureIgnoreCase))
            policy.Origins.Add($"{referrer.Scheme}://{referrer.DnsSafeHost}");
        else
            policy.Origins.Add($"{referrer.Scheme}://{referrer.DnsSafeHost}:{referrer.Port}");

        // Add custom headers that should be exposed
        foreach (var exposedHeader in exposedHeaders)
        {
            policy.ExposedHeaders.Add(exposedHeader);
        }

        return Task.FromResult(policy);
    }
}

Use it like this:

var corsPolicyProvider = new IdenticalRootDomainCorsPolicyProvider();
corsPolicyProvider.CorsPolicyError += CorsPolicyProviderOnCorsPolicyError;

configuration.EnableCors(corsPolicyProvider);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM