Home > Mobile >  how to restrict cross origin request for other domains using CORs
how to restrict cross origin request for other domains using CORs

Time:03-25

I am working on asp.net web api project I want allow only my domain access but its working fine when i calling my webapi from JavaScript but problem is when i calling web api from c# code it allows any domine to access how can i restrict this i want give access only for my domain

I am working on asp.net web api project I want allow only my domain access but its working fine when i calling my webapi from JavaScript but problem is when i calling web api from c# code it allows all domine to access how can i restrict this..? i want give access only for my domain

CodePudding user response:

You can use Microsoft.AspNet.WebApi.Cors, a Nuget package from Microsoft. Follow these step:

  1. install package for your API project.

  2. add one line code to your App_Start/WebApiConfig.cs file to enable the function: config.EnableCors();

    using System.Web.Http;
    namespace WebService
    {
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // New code
                config.EnableCors();
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    }
    
  3. use attribute in your controller or action like this:

    using System.Net.Http;
    using System.Web.Http;
    using System.Web.Http.Cors;
    namespace WebService.Controllers
    {
        [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
        public class TestController : ApiController
        {
            // Controller methods not shown...
        }
    }
    

You can get more info here

CodePudding user response:

1=> var cors = new EnableCorsAttribute("http://mydomain", "*", "*"); config.EnableCors(cors); I wrote this code in web config file as global level but its working fine when I am calling my web api from client side its allowing only for specified domain

2=> This is my Client side code

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$ $.ajax({
                url: "http://localhost:49676/Account/ValidLogin",
                method: "get",
                data: Employee,
                dataType: "json",
                //contentType: "application/json",
                success: function (data) {
                    GetAllEmployee(data);

                    alert("success");
                    console.log(data);
                },
                error: function (err) {
                    alert("error");
                }
3. I wrote some code I web config file to restrict other domain request but when i calling web api by client side it allowing any domine to access so my problem is I want to restrict my api form Other public domain

Here is my server side code

protected void btnDelete_Click(object sender, EventArgs e) {

        string strUrl = string.Format("http://mydomain/account/validlogin?username=admin&password=admin");
        HttpWebRequest requestObjectGet = (HttpWebRequest)HttpWebRequest.Create(strUrl);
        requestObjectGet.Method = "GET";
        HttpWebResponse responseObjectGet = null;
        responseObjectGet = (HttpWebResponse)requestObjectGet.GetResponse();

        string strresulttest = null;

        using (Stream stream = responseObjectGet.GetResponseStream())
        {
            StreamReader sr = new StreamReader(stream);
            strresulttest = sr.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            string StrToken = js.Deserialize<string>(strresulttest);
            Session["ApiToken"] = StrToken;

}

  • Related