I have to send credentials to authenticate on the server (windows authentication) for my application:
with-credentials = true
The problem is that my clients are mobile devices, and I can't tell to the server in Access-Control-Allow-Origin the origin domains.
I would like to do that:
Access-Control-Allow-Origin = *
But I know it is not possible because of security issues.
How can I do that with HTTP?
PS: I am using a server in ASP.NET and clients are made with Ionic (Angular). Currently, I am using a temporary solution:
Access-Control-Allow-Origin = localhost:8100
But when I will deploy the application it won't work on real devices.
From enable-cors.org:
CORS In ASP.NET
If you don't have access to configure IIS, you can still add the header through ASP.NET by adding the following line to your source pages:
Response.AppendHeader("Access-Control-Allow-Origin", "*");
See also: you can also Configure IIS6 / IIS7
Reference Taken
Sometimes you need to check this wihtin your AuthorizeAttribute
// pre-flight request (OPTIONS) are always ok.
// https://stackoverflow.com/questions/26296779/chrome-v37-38-cors-failing-again-with-401-for-options-pre-flight-requests#28235624
if (actionContext.Request.Method == System.Net.Http.HttpMethod.Options)
{
return true;
}
Related
I've been using a Self-Hosted SignalR Windows service accessed from multiple production servers (now in Azure) for 6+ years without a problem. I created an identical server for development in Azure but when I'm accessing SignalR from a browser on the SAME SERVER, SignalR gives me the following error when using either http:6287 or https:6286:
Access to XMLHttpRequest at 'http://myserver.learn.net:6287/signalr/negotiate?clientProtocol=1.5&xxxxxxx' from origin 'http://myserver.learn.net' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
However... It WORKS when connecting from OTHER SERVERS! I'm starting the connection with no errors using:
SignalR = WebApp.Start("http://myserver.learn.net:6287/");
SignalRSSL = WebApp.Start("https://myserver.learn.net:6286/");
(also SignalR = WebApp.Start("*:628x/" for both);
In my client code, I include the following script:
<script src="http://myserver.learn.net:6287/signalr/hubs"></script>
When I enter that url (or https version) in a browser ON THE SAME OR DIFFERENT SERVER, it shows the ASP.NET SignalR JavaScript Library v2.3.0-rtm page correctly! I've turned off the firewall with no change, added Microsoft.Owin.Host.HttpListener (someone suggested). I have also entered the wildcard certificate with netsh so the SignalR service can deal with the SSL connection using:
netsh http add sslcert ipport=0.0.0.0:6286 appid={12345678-db90-4b66-8b01-88f7af2e36bf} certhash=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Edit: I've also tried changing the ipport value to the real internal IP of the server as well as the public IP but no change.
So, why can't I access SignalR from the same server?
I found a solution in another answer here that worked. I changed:
$j.connection.hub.start().done(function () {
To:
$j.connection.hub.start({ jsonp: true, xdomain: true }).done(function () {
Which worked for both internal and external clients. xdomain:true alone didn't work but when I added jsonp:true it did. I have no real idea why, just that it's working now.
I have a few web applications under the same domain, all using a stand alone Identity Server 3 app for login purposes. Under test environment, every single one of then are under the same domain (http://192.168.100.1, or by dns http://companyServer).
Recently, one application needed to request some data from another app, and I found the following error when debugging on Visual Studio:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://companyServer:60000/MyApp/Api/Company/Info?parameter=123. (Reason: CORS header 'Access-Control-Allow-Origin' not present).
We have a central library responsible for configuring Web API on our systems, it has the following (among other things):
public static IAppBuilder UseCebiUtilWebApi(this IAppBuilder app, CebiWebApiOptions options)
{
Logger.Debug("Configuring Web API");
app.UseCors(CorsOptions.AllowAll);
...
}
On the same method, we also configure Identity Server.
I also checked on my Login Server App, and there is the following code regarding CORS:
public class CompanyCorsPolicyService : DefaultCorsPolicyService
{
public CompanyCorsPolicyService()
{
base.AllowAll = true;
}
}
This method is being called on the project's Startup.cs.
As far as I know, every single end of my environmet should be enabling full CORS access, no matter the origin. But the header is still missing.
I've tried quite a few solutions on the internet:
Using "config.EnableCors" instead of "app.UseCors"
Overriding GrantResourceOwnerCredentials,
I have also tried setting up manually some CORS related headers on Web.Config, but I was unable to find the specific question here on SO.
I don't think identity server is related to this problem, but since that is the difference between my evironment and the solutions I've found, I decided to put it in here too.
Any ideas?
It's possible that the OPTIONSVerbHandler could be intercepting all OPTIONS (CORS pre-flight) requests.
Try disabling that so that ASP.Net can handle those requests instead.
I am learning Web-Based Programming and currently chose to work on Asp.Net Core 2.0.
I had successfully created a Web App with 2 layers of Controllers Home & API.
The Home Controller interacts directly with my Views while the API controller is called using GetAsync, PostAsync, PutAsync, etc. from my Home controller.
Recent I decided to move this app into HTTPS. Learned about self-signed certificates and had successfully gotten it to run except my API becomes inaccessible.
With SSL switched off, I could still call my API with Postman.
I used to call my API using this URI: http://localhost:5667/api/WebApi.
var response = client.GetAsync(“SomeApi”)
response.Wait();
Now I tried using URI: https://localhost:5667/api/WebApi but breaks at response.Wait().
Any advice, please. Thanks in advance
As requested: here’s a portion of my Startup.cs
services.AddMvc(
options =>
{
options.SslPort=5667;
options.Filters.Add(new RequireHttpsAttribute());
}
);
services.AddAntiforgery(
options =>
{
options.Cookie.Name=“_af”;
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy=CookieSecurePolicy.Always;
options.HeaderName=“X-XSRF-TOKEN”;
}
)
HTTP and HTTPS cannot be served over the same port. If your localhost HTTP endpoint is on 5667, then likely your HTTPS endpoint is on 5668 - though you can check the port number for yourself in the info that Kestrel will log on startup.
In production, HTTP is typically served over port 80, while HTTPS is served over port 443. These are the defaults if you don't specify otherwise.
Separately, you might want to consider enabling HTTPS redirection in your Configure block:
app.UseHttpsRedirection();
I'm testing my own Web API service, and after adding of
[Authorize(Roles = "MyRole")]
to the controller, all requests made by HttpClient fails with "Unauthorized" (401). Service is hosted in IIS Express with Windows authentication enabled, as suggested here.
Client sends appropriate request header:
var authHeaderParameter = Convert.ToBase64String(Encoding.ASCII.GetBytes("MyUser:MyPassword"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderParameter);
The same request (at least, the same URI and credentials) made from browser works as expected and returns data.
Fiddler shows, that browser sends "Proxy-Authorization" request header, and doesn't send any "Authorization".
What am I doing wrong?
How to fix request using HttpClient?
UPD.
This doesn't help too:
var handler = new HttpClientHandler
{
UseProxy = false
};
var client = new HttpClient(handler, true)
{
BaseAddress = new Uri(baseAddress)
};
Well, the problem was located inside IIS Express settings.
I'll post this answer and shall add "VS 2015" tag into question, because it might be helpful.
Thanks to #swiley, WireShark and npcap (the last is needed to capture loopback interface traffic via WireShark).
Inspecting response headers, that were sent to web browser, I've found, that 401 responses contain Autorization: NTLM headers. Since browser automatically handles this case, it sends current NTLM credentials in further requests and get the requested data. My HttpClient code does not, and, actually, must not handle NTLM.
Prerequisites.
First of all, this is VS 2015 and my Web API project uses IIS Express for hosting, which is the default setting. Non-default here is that I've changed port to the constant value:
The second, IIS express in VS 2015 stores its configuration in %SolutionDir%\.vs\config\applicationhost.config file. Note, that this was changed from previous versions.
The third.
Project properties, available on F4 key press, are very limited, and, in fact, you're just modifying the same applicationhost.config from above:
The fourth, this post doesn't helps:
To enable Basic authentication using IIS, set the authentication mode
to "Windows" in the Web.config of your ASP.NET project:
While this will work with "mature" IIS, Visual Studio + IIS express just ignore these settings.
The solution.
Open %SolutionDir%\.vs\config\applicationhost.config in text editor.
Find first <authentication> tag.
Under it, find <basicAuthentication enabled="false" />, and change enabled to true.
Save file.
Restart Web application.
Note, that properties you can see by pressing F4 are stored under <location path="YourProjectName"> tag.
By default, it has sub-tag authentication, but without basicAuthentication:
<authentication>
<windowsAuthentication enabled="false" />
<anonymousAuthentication enabled="false" />
</authentication>
If solution has more that one IIS Express-hosted project with custom authentication settings, one should add basicAuthentication into project-related section instead of first <authentication> tag, which is global config per solution.
I would post a comment but my reputation is too low, in the past I've had this problem when the server sent back an http redirect and the http library automatically sent back my request without the custom header data. I think the request or response object will have a uri field if this happens, you can also disable automatic redirection handling. I ended up figuring all this out using wire shark though and I highly suggest you do that next.
I have a one page ASP.NET 4.0 C# script running. In debug mode my script works just fine but when I publish it, it seems like it is not sending the credentials when making the WebRequest.
The following is the code I am using, I have tried a bunch of things but I keep getting a 401 Unauthorized when I am using my published version of the script. BTW I am using IIS 7
WebRequest fwRequest = HttpWebRequest.Create(fwURL);
fwRequest.UseDefaultCredentials = true;
//fwRequest.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse myHttpWebResponse = (HttpWebResponse)fwRequest.GetResponse();
While debugging, your project use your credentials, but when you publish it it will use the credentials of ASP.NET user, or the credentials set in IIS configuration.
So no, you can not pass credentials of your client to another web service/appliaction unless you convince him/her to pass username-password to your application (Except that both web apps are on the same machine).