简体   繁体   中英

CORS not working ASP.Net MVC5

I am trying to block cross-domain access to my resources using CORS. I have tried WebApi.Cors and custom ActionFilter too. But I am still able to access the data from not allowed domains.

My ActionFilter code is below

public class AllowCrossSiteAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "https://example.com");
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "*");
            base.OnActionExecuting(filterContext);
        }
}

My Controller

    [HttpGet]
    [AllowCrossSite]
    public ActionResult Index(string username)
    {
      //return json data
    }

These headers are present in the response headers but why the request is not blocking from other domains, what am I doing wrong? Please help

Adding the response headers will not actually provide any sort of security. Regular cors implementations only add those response headers to inform the client about the cors rules that were applied.

Something on the server needs to compare your cors rules to the origin / method etc headers of the request, and then send back a 4XX response if they don't match up.

The NuGet package Microsoft.AspNet.WebApi.Cors allows you to do something like this:

[EnableCors(origins: "https://example.com")]

If you prefer to do your own custom implementation, you can see the source code for this attribute on github . That should give you a fairly good idea of what you need to do to make cors work by hand. It's simpler than it looks, really.

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