I Implemented an AngularJS Project. The Server Side I coded using .NET Web API (C#). I Enabled the CORS in the Web API by installing the NuGet Package https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class SampleController : ApiController
{
[AllowAnonymous]
[HttpGet]
public string GetAnonymousString()
{
FormsAuthentication.SetAuthCookie("Sample AllowAnonymous", false);
return "Calling AllowAnonymous Method using CORS - Public Text";
}
[Authorize]
[HttpGet]
public string GetAuthorizeString()
{
return "Calling Authorize Method using CORS - Private Text";
}
}
I hosted the client Side Application in http://localhost:8050 and I hosted Service Web API in http://localhost:8060.
Now I tried to access the GetAnonymousString() - http://localhost:8060/api/Sample/GetAnonymousString its working fine and also it returns the httponly cookie to the client via response.
But I tried the same for GetAuthorizeString() - http://localhost:8060/api/Sample/GetAuthorizeString, it returns 401 Unauthorized error as a response.
If I hosted Client App and Web API in the same domain, then its working fine. Only issue is CORS.
Kindly assist me how to use the Authorize in CORS ???
Related
I found a lot of pages regards to this issue, but none of the Solutions worked.
I have a JavaScript Button in the View that is calling a WebApi method(C#)
$('#btn-Sign-in', this).click(function () {
var apiUrl = 'https://localhost:44391/api/test';
fetch(apiUrl).then(response => {
return response.json();
}).then(data => {
// Work with JSON data here
console.log(data);
}).catch(err => {
// Do something for an error here
});
});
This is My Webapi method that is calling external api:
[RoutePrefix("api")]
public class TestController : ApiBaseController
{
[HttpGet]
[Route("redirectforauth")]
[RequiresPermission("Home:View")]
[HttpGet]
[Route("test")]
[RequiresPermission("Home:View")]
public async Task<IHttpActionResult> ConnectExternal()
{
var request = new FlurlRequest("URL of an external website")
.SetQueryParam(...)
.SetQueryParam(...)
.SetQueryParam(...)
.SetQueryParam(...);
var redirectUrl = request.Url.ToInvariantString();
return Redirect(redirectUrl);
}
when I am running the project, I am getting this error:
CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
This error is due to your web application URL & C# API URL are not having same origins (not running on same port or same hosts). Two URLs have the same origin if they have identical schemes, hosts, and ports.
EX: Your C# URL https://localhost:44391 is different from your web application URL.
First, to make sure that you are getting the error due to your c# api & not due to the external api, comment out your external api request code inside your action, and return something directly from your api to web application. (If the error is from external Api, that external api needs to handle this to allow access to other origins.)
If you are getting the error due to your c# api & not due to the external api, one approach to do this is, by enabling CORS in your C# WebApi application. You can enable CORS per action, per controller, or globally for all Web API controllers in your application.
You can install this nuget package in your C# API application:
Microsoft.AspNet.WebApi.Cors
In App_Start/WebApiConfig.cs, add this code to the WebApiConfig.Register method:
config.EnableCors();
Next, add the [EnableCors] attribute to your TestController class, with your web application URL.
Ex: if your web application URL is localhost:3000, add it in origins as below.
[EnableCors(origins: "http://localhost:3000", headers: "*", methods: "*")]
public class YourController : ApiController {
// Your methods...
}
Now the AJAX request from your Web Client should work. The GET, PUT, and POST methods are all allowed.
For more details on how to enable CORS & how it works:
Enable cross-origin requests in ASP.NET Web API 2
I've been stumped on this one for a few days now. I am a beginner to CORS so navigating this has been very confusing.
What's going wrong: I created a asp.net web api which can successfully send POST requests to my SQL database. I have used POSTMAN to send the data successfully. Once I enable CORS I can no longer send the data. I receive a 400 Bad Request.
Some References of my code:
My Controller which handles the POST request:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ClientsDataAccess;
namespace MS_Clients_Post.Controllers
{
public class ClientsController : ApiController
{
public HttpResponseMessage Post([FromBody] Client client)
{
try
{
using (NewlandiaEntities entities = new NewlandiaEntities())
{
entities.Clients.Add(client);
entities.SaveChanges();
var message = Request.CreateResponse(HttpStatusCode.Created, client);
message.Headers.Location = new Uri(Request.RequestUri +
client.Id.ToString());
return message;
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
}
}
My webAPIconfig.cs file (where I enabled CORS):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
namespace MS_Clients_Post
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
//enabling cors. The "*","*","*" attributes allow all to access. This should be more limited acccess in the future.
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
//end of cors code.
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
What I'm seeing in Fiddler:
OPTIONS Response 200 (Only returned with Angular APP, not POSTMAN
along with POST Response 400 BAD REQUEST (With POSTMAN or Angular APP
TLDR;
POST request using ASP.net Web API works before enabling CORS. Why doesn't it work after?
Any help is greatly appreciated!
I found the solution to my problem. This was a failure to identify what was actually going wrong. Couple different things:
When my application was deployed by VSTS to my development webserver it removed the SQL server login credentials from IIS application. (Advanced settings on IIS application pool).
Secondly and more importantly, the Syntax of my Angular Application was indeed not correct. Therefore the syntax was wrong from the Angular Application, but correct from POSTMAN (in postman I would use a GET method to get the JSON from server, and copy-paste the JSON to do a POST request).
Lesson learned, if it says 400 Bad Syntax, double check the syntax of what you are sending!
I want to open webSocket by web api post request.
I tryed to use HttpContext.Current.AcceptWebSocketRequest but it didn't work (as you can see in the following example) because HttpContext.Current is null in self host.
public class ChatController : ApiController
{
public HttpResponseMessage Get(string username)
{
HttpContext.Current.AcceptWebSocketRequest(new ChatWebSocketHandler(username));
return Request.CreateResponse(HttpStatusCode.SwitchingProtocols);
}
}
Is there a way to get the current http context without IIS?
Or what is the best way to open websocket?
I am working on Console Application and, I am calling a web API from console application to put data onto the web API but when I am getting the data using GetAsync() method I am able to get the data and when I am putting the data also able to put data while the web API is not hosted on IIS
After hosting on IIS I got the status code 405 "Method not allowed"
I have also tried enabling cors inside web API config in a register()
config.EnableCors();
and
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ValuesController : ApiController
Any help will be Appreciated.
Thanks
I was putting the data onto Web API using PutJsonAsAsync(), but It doesn't work with PutJsonAsAsync() I don't know why but when I used PostAsJsonAsync() it works for me.
thanks
I have MVC application and a Web Api hosted on different server. But i am not able to authenticate my web api's using ADFS if accessed from my mvc web app.
Getting "CORS Error"
Thanks in advance
You need to add Nuget Package Microsoft.ASP.Net.Cors and add [EnableCors("", "", "*")] attribute to your controller class
[EnableCors("*", "*", "*")]
public class YourController : ApiController
{
}
Add this in WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
config.EnableCors();
}
You may check this Link.
Please do not add a CORS filter with "*" (wild cards to allow any IP/Domain..).
Owasp's Cheat Sheet has some handy pointers and further information: https://www.owasp.org/index.php/HTML5_Security_Cheat_Sheet#Cross_Origin_Resource_Sharing