ASP.NET - consume web service - https only - how? - asp.net

I have web services built with ASP.NET and ASP.NET clients consuming them. When consuming the webservices, how would I to force the clients to use https?
I don't want to force the whole site to use https by turning on require SSL in IIS.
Can I use the IIS7 URL rewrite module to re-route http requests to https?

No, you cannot use URL rewriting to change the protocol.
Instead, you could just implant a check in your web service and throw an exception if the protocol is HTTP.

Any chance you can add your webservices to a virtual directory and just force the virtual directory to use SSL? Along with checking inside the webservice calls as Fyodor suggest, you could add a check in Application_BeginRequest in your global.asax, although it's not very tidy:
void Application_BeginRequest(object sender, EventArgs e)
{
if (!Request.IsSecureConnection && Request.Url.ToString().Contains(".asmx"))
{
string secureUrl = Request.Url.ToString().Replace("http:", "https:");
Response.Redirect(secureUrl);
}
}

Related

IIS/ASP.NET receiving calls from external application to SOAP proxy server

This is a weird one, sorry :( I have a remote server (3rd party, not under my control) that calls a defined endpoint (http://myservice.com/service.asmx), but internally before calling, it appends '.wsdl' to the URL string (so I see http://myservice.com/service.asmx.wsdl) The original server waiting for this request is expecting this, but the original server is no longer in service and I'm hoping to replace it with a 'stub'.
Basically, I'm trying to put an ASP.NET application in place to receive the requests (all currently running locally with IIS). I've used wsdl.exe to create my stub code, and it's called service.asmx. Using POSTMAN against this running service, it all works great - I can debug, see the responses etc, but if I try to rename my project to service.asmx.wsdl to accomodate for the real server making the request, I see a 405 - HTTP Verb error. I've been unable to figure out how to make this work and was thinking it's IIS handers or something like that. I've looked at IIS handers, but I can't seem to find one that would work (i.e., copying the .asmx profiles into newly created .wsdl profiles)
So my question is "Can I make the endpoint at .wsdl behave like it's an .asmx or am I approaching this all wrong?
After much hairpulling, I had to add Global.asax file to my project and implement the following method therein...
protected void Application_BeginRequest(object sender, EventArgs e)
{
var path = Request.Path;
if (path.EndsWith(".asmx.wsdl"))
Context.RewritePath(path.Replace (".asmx.wsdl", ".asmx"));
This allowed for the default asmx handlers in IIS to remain as-is and process the request from the URL by simply rewriting the URL programmatically.

Remove query strings from static resources

My website is running on ASP.NET platform and recently i test my website on pingdom and i found the below error.
Resources with a "?" in the URL are not cached by some proxy caching
servers. Remove the query string and encode the parameters into the
URL for the following resources:
https://projectsdeal.co.uk/ScriptResource.axd?d ...
63Nawdr4rAt1lvT7c_zyBEkV9INg0&t=ffffffffe3663df5
https://projectsdeal.co.uk/ScriptResource.axd?d ...
JGTlZFM0WRegQM9wdaZV3fQWMKwg2&t=ffffffffe3663df5
Simple leave it as it is (its not an error !) - you can not remove this query string from resource because this is the id on how to load that resource from asp.net
The message that you get is actually talk for a proxy caching servers - what is a proxy caching server ? a middle computer that cache pages of your site, not the actually client computer - that can hold in cache that page and not bring slower your site in general.
So your client can hold that resource on cache if you set them correctly, and from what I see asp.net take care correctly and you resource are cached just fine - see this screen shot.
Now if you wish to add even more aggressive cache you can use the global.asax and do something like
protected void Application_BeginRequest(Object sender, EventArgs e)
{
string cTheFile = HttpContext.Current.Request.Path;
if (cTheFile.EndsWith("WebResource.axd", StringComparison.InvariantCultureIgnoreCase))
{
JustSetSomeCache(app);
}
}
private static void JustSetSomeCache(HttpApplication app)
{
app.Response.Cache.AppendCacheExtension("post-check=900, pre-check=3600");
app.Response.Cache.SetExpires(DateTime.UtcNow.AddHours(32));
app.Response.Cache.SetMaxAge(new TimeSpan(32, 0, 0));
app.Response.Cache.SetCacheability(HttpCacheability.Public);
app.Response.AppendHeader("Vary", "Accept-Encoding");
}
What is the different ? The second cache is not check the server at all for file change as the asp.net do, you can gain one webserver call.

Rerouting http traffic in ASP.NET application

I would like to re-route traffic in HTTP request from one server to another in an ASP.NET web site. I have been looking into trying to do this using an http module or http handler. Are these viable options for my case or does anyone have a better recommendation? This application is using .NET 4.0 Framework and is host on IIS6.
In addition to the comment above, I wanted to provide a small snippet of code. You should be able to do this in your HTTPModule with Response.Redirect. I am not 100% certain but I believe that the RewritePath method may throw a platform not supported exception on IIS6. IIS6 definitely support Response.Redirect fortunately.
Go ahead a handler for begin request:
{
context.BeginRequest += new EventHandler(MyBeginRequestMethod);
}
Then in your begin request method:
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
if(context.Request.FilePath.Contains("someresource"))
{
context.Response.Redirect("http://www.google.com");
}
Obviously you will be able to do some more comprehensive look-up of content and a more complete redirect this way.

getting https to work locally in asp.net MVC4 application

I followed this tutorial exactly:
http://www.hanselman.com/blog/WorkingWithSSLAtDevelopmentTimeIsEasierWithIISExpress.aspx
But when I am running locally and try to navigate from a non-https page (like home/index) to and a page I decorated with [RequireHttps] I get the generic "SSL connection error" message.
I hate posting such a generic question, but can you think of anything I have missed? It is a large asp.net mvc4 application, I enabled ssl in the project, it shows the ssl url. Navigating to the ssl url manually does not work either.
HALP!
NOTE: Using IIS Express with visual studio 2012
Per the comment, the error I am getting is Cannot Establish SSL connection.
You shouldn't be using Https when testing locally. I've created my own Https Filter where it will ignore all the local traffic in the localhost and only works either on staging and live environment. You can modify the code to suit you need.
public class RequireSSLAttribute : FilterAttribute, IAuthorizationFilter {
public virtual void OnAuthorization(AuthorizationContext filterContext) {
if(filterContext == null) {
throw new ArgumentNullException("filterContext");
}
if(!filterContext.HttpContext.Request.IsSecureConnection) {
HandleNonHttpsRequest(filterContext);
}
}
protected virtual void HandleNonHttpsRequest(AuthorizationContext filterContext) {
if(filterContext.HttpContext.Request.Url.Host.Contains("localhost")) return;
if(!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) {
throw new InvalidOperationException("The requested resource can only be accessed via SSL");
}
string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
//ignore if the request is from a child action
if(!filterContext.IsChildAction) {
filterContext.Result = new RedirectResult(url);
}
}
}
And this is how you use it...
[RequireSSL(Order=1), Authorize(Order=2)]
public PartialViewResult AccountHeader() {
blah...blah...
}
I know it's already answered, but I thought I'd point out the cause of the original error, which the other answers omit.
When you enable SSL on IIS Express, your site is hosted on 2 ports, 1 for http and another for https. When you debug in Visual Studio, the port is usually specified explicitly. The links on your site probably don't specify port numbers, so when you link from a plain http page to a https one, the port number won't change, and you'll request a https page on the plain http port. This is why you get the SSL connection error.
On a real server the port numbers should be implicit, so the problem shouldn't come up, but you'll need to make sure you're using the right port when debugging locally.
You need to add ssl certificate to your site instance in IIS.
To create certifiacte and add it to IIS7 try this tutorial: http://technet.microsoft.com/en-us/library/cc753127(v=ws.10).aspx
After creation you'll be able to add it to your website. Open in IIS 'your website' -> Bindings -> Add and add new host header. Select https, port 443 and select created sertificate.

Difference between http and https technique

Does it need Certificate/License/Registration before launching the website using https?
I want to use the mentioned code in Global.asax file.
protected void Application_BeginRequest(Object sender, EventArgs e)
{
Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"]
+ HttpContext.Current.Request.RawUrl);
}
First of all, I think you will never reach it, as it will loop in the Application_BeginRequest over and over as you are redirecting all requests...
Maybe what you're after is redirecting if the request comes from a non secure connection (http), no?
for that, see if the request comes from such connection like:
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (!HttpContext.Current.Request.IsSecureConnection)
Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri.Replace("http://", "https://"));
}
Secondly, the HTTPS protocol needs to be up and running or you will get a ERR_SSL_PROTOCOL_ERROR error thrown.
In Visual Studio, you can easily enable https in the project properties
and you will get the untruest warning
As Visual Studio generated (on installation) a default self signed certificated.
In production environment you will need to:
if it's an intranet application, just use the self-signed certificate
on a internet application, you do need to buy an SSL certificates, now-days they re cheaper and cheaper...
From your comments I have some question myself now...
Do you understand what HTTPS does to the connection between client computer and server?
Do you really need a secure connection between the two?
What kind of data are you trying to secure?
When you want to use secure HTTP (using the HTTPS protocol) you say that the traffic between the browser and server is encrypted.
This means you need a certificate on the server so that the browser and server can decide on how to encrypt the traffic.
This has nothing to do with redirects and everything to do with your server setup.

Resources