Disable security for a HttpHandler in IIS7 - asp.net

I have created a custom http handler (IHttpHandler).
This handler can be called from any place in the application.
eg: domain.com/file.handlerExtension or it can be domain.com/folder/file.handlerExtension
I have security on my application, but this handler should be available to anonymous users also. Because of this approach it is a mess to create a location element in web config for every posible location from where the handler can be called.
Is there a way to remove check of Authentication and Authorization on a specific resource or Handler in IIS7?

As far as I know - No - this is handled as an HttpModule (if not using iis authentication) - the application configuration defines urls to protect. The only hope may be to hack it so it thinks the user is already authenticated (not even sure if it would work) prior to the Authentication httpModules running which would mean changing processing order. and even then you would have to have some logic built in to say 'force authentication for a request to THIS uri'
MVC's security handling is a bit better IMHO as you can simply use attributes on your controllers or methods to define security and in that case your app would simply remain anonymous for those request.

Related

How to perform full redirection inside IIS (without a browser roundtrip)?

In the standard redirection scenario, the browser is sending another request to the server.
How to achieve internal IIS redirection with all web application lifecycle events (BeginRequest, AuthenticateRequest, ...) to be retriggered (not just calling the another handler)?
CLARIFICATION: I mean just redirection inside the same web app.
It depends where in the page lifecycle you are. Within a page you can use server.transfer, but it won't work with MVC & it's a bit hacky.
The context has some methods, such as rewritepath that let you change the path that is executing, but again, there are limitations.
iis.net has a useful article on this.

TransferRequest vs Transfer in ASP.Net

I have gone through the links mentioned below,
iis forum and HttpModules & Server.Transfer / Server.TransferRequest / RewritePath problems. but unable to catch the concept behind these transfer methods.
How are they works? And which one is preferred in different situation?
Can someone explain me TransferRequest vs Transfer methods for server side transfer in asp.net and its roles?
Thanks in advance
HttpServerUtility.Transfer Terminates execution of the current page and starts execution of provided URL.
This basically maps and executes a new ASP.NET Page (or serves a static file) corresponding to the url provided. It does this in-place in the current request pipeline, without applying new configuration to the new url, or re-running IIS modules for the new url. Because of this, its very fast, but it also prevents a lot of scenarios that are possible with TRQ.
HttpServerUtility.TransferRequest Performs an asynchronous execution of the provided URL.
This is a full IIS child request under the covers, which allows it to re-run the entire request pipeline for the new request as if it was a separate request, getting the correct configuration for it, and running all of the normal IIS modules including authentication, authorization, etc. For example, IIS will apply the authorization rules for the new url, as opposed to the previous url.
TransferRequest re-runs the entire request pipeline as if it were a separate request. This means that IIS and ASP.NET modules are re-applied; authentication and authorization rules for the new URL will be honored. Note that TransferRequest requires the integrated pipeline mode of IIS 7+, and the transfer can be to an ASP page or another resource like an XML file.
Transfer transfers execution from one ASP page to another ASP page on the server. Unlike TransferRequest, IIS and ASP.NET will NOT verify that the current user is authorized to view the resource delivered by the Transfer method. If you need to force reauthorization, and integrated pipeline mode is not an option, call Redirect instead of the Transfer method. Redirect triggers a client-side redirect so that the new request will be subjected to all authentication and authorization logic of IIS and ASP.NET.

How can I add custom HttpOperationHandlers to MVC 3 REST server?

My back-end server is built using the Microsoft WCF REST Starter Kit Preview 2. I want to add some request processing to all requests, except for those methods I explicitly disable by marking them with an attribute. I have over a hundred service methods and there are only a few I want to exclude from this extra processing. I'll tag them all if I have to, but I'm trying to avoid disrupting what's already written.
I haven't seen anything I can add to WebInvoke, and adding an interceptor won't let me examine the method that the request is routed to.
I am asking for an explanation of how to register HttpOperationHandler object(s) so I can do my extra request processing (i.e. authorization based on information in the request headers) before it is handed off to the method it was routed to. Can someone please explain how to do this, without rewriting my existing codebase to use Web API?
You can't use an HttpOperationHandler with WCF REST Starter Kit. However the Web API is very compatible with ServiceContracts that were created for WCF REST Starter kit. You should be able to re-host them in a Web API host relatively easily. You may have to change places where you access WebOperationContext, but it should not be a huge change.
I solved my problem by adopting another method. It authenticates all requests. I can't control which method it applies to, but I was able to work around that.
I created a custom ServiceAuthorizationManager class to process the Authorization header. The CheckAccess() method returns true to allow the request through or false if the user is not authenticated or not authorized to perform the service. I hooked it up to the ServiceHost for my services by creating a custom WebServiceHostFactory class and assigning an instance to the Authorization.ServiceAuthorizationManager in its CreateServiceHost() methods.
Although I can't directly check method attributes for the service being executed, the Message.Headers member of the object passed to CheckAccess() has a To property that contains the URI of the service being called. If necessary, I could examine it to determine what method the request would be routed to.
The ServiceAuthorizationManager applies to all requests, so no web methods or classes must be marked with any special attributes to enable it.

HTTP handler vs HTTP module

Can someone explain in less than 2 sentences the difference between both? Yes, I know google can provide hundreds of answers but not one in 2 clear sentences:)
HttpHandler is where the request train is headed. HttpModule is a station along the way.
The two sentences:
An HttpModule will execute for every request to your application, regardless of extension, and is generally used for things like security, statistics, logging, etc.
An HttpHandler is generally associated with a specific extension, and is used for things like RSS feeds, dynamic image generation or modification, and the like.
A little more explanation if that's not completely clear:
The way I think about them - modules "plug in" to the request pipeline, whereas handlers "handle" a specific file extension. So, if you've got a site with a LoggingModule and a PdfHandler, both will execute for a request to http://example.com/sample.pdf, and the logging module alone will execute for a request to http://example.com/page.aspx.
There's a pretty clear article on the difference on MSDN: HTTP Handlers and HTTP Modules Overview
The prime and common goal of HttpHandler and HttpModule is to inject pre-processing logic before the ASP.NET request reaches the IIS Server.
ASP.NET provides two ways of injecting logic in the request pipeline;
Http Handlers:
Http Handler helps us to inject pre-processing logic based on the extension of the file name requested. ASP.NET uses HTTP handlers for implementing a lot of its own functionality.For example, ASP.NET uses handlers for processing .aspx, .asmx and trace.axd files.
example:
RSS feeds: To create an RSS feed for a Web site, you can create a handler that emits RSS-formatted XML. So when users send a request to your site that ends in .rss, ASP.NET calls your handler to process the request.
There are three steps involved in creating Handler
1. Implement IHttpHandler interface.
2. Register handler in web.config or machine.config file.
3. Map the file extension (*.arshad) to aspnet_isapi.dll in the IIS.
IHttpHandler interface has ProcessRequest method and IsReusable property which needs to be implemented.
ProcessRequest: In this method, you write the code that produces the output for the handler.
IsResuable: This property tells whether this handler can be reused or not.
You can register the handler in web.config file like this
<httpHandlers>
<add verb="*" path="*.arshad" type="namespace.classname, assemblyname" />
</httpHandlers>
Note: here we are handling any file name with extension arshad.
Http Modules:
HttpModule is an event based processor to inject pre-processing logic before the request reaches the IIS Server. ASP.NET uses HTTP Module to implement lots of its own functionality like authentication and authorization, session management and output caching etc.
ASP.NET engine emits lot of events as the request passess through the request pipeline.
Some of those events are AuthenticateRequest, AuthorizeRequest, BeginRequest, EndRequest.
By Using HttpModule you can write logic in these events. These logic get executed as the events fire and before the request reaches IIS.
There are two steps involved in creating Modules,
1. Implement IHttpModule interface
2. Register module in web.config or machine.config file
example:
Security: Using HTTP module, you can perform custom authentication or other security checks before the request reaches IIS.
HTTP handler is the process that runs in response to a request made to an ASP.NET Web application.
HTTP modules let you examine incoming and outgoing requests and take action based on the request.
HttpHandler is responsible for handling http request by extension while HttpModule is responding to application life cycle events.
Nice article aboute it HttpModule-and-HttpHandlers
Reference: INFO: ASP.NET HTTP Modules and HTTP Handlers Overview
“Modules are called before and after the handler executes. Modules enable developers to intercept, participate in, or modify each individual request. Handlers are used to process individual endpoint requests. Handlers enable the ASP.NET Framework to process individual HTTP URLs or groups of URL extensions within an application. Unlike modules, only one handler is used to process a request”.
HTTP handler is where actually compilation is done based on setting. such as if page extension is .aspx then it will compile through system.web.Ui.Pagahandlefactory. once compilation is done at HTTP handle request will go though HTTP module and IIS.
HTTP Handler
HTTP Handler is the process which runs in response to a HTTP request. So whenever user requests a file it is processed by the handler based on the extension. So, custom http handlers are created when you need to special handling based on the file name extension. Let's consider an example to create RSS for a site. So, create a handler that generates RSS-formatted XML. Now bind the .rss extension to the custom handler.
HTTP Modules
HTTP Modules are plugged into the life cycle of a request. So when a request is processed it is passed through all the modules in the pipeline of the request. So generally http modules are used for:
Security: For authenticating a request before the request is handled.
Statistics and Logging: Since modules are called for every request they can be used for gathering statistics and for logging information.
Custom header: Since response can be modified, one can add custom header information to the response.

IIS - Different processing of default document in Integrated Pipeline mode?

I have an HTTP Module to handle authentication from Facebook, which works fine in classic pipeline mode.
In integrated pipeline mode, however, I'm seeing an additional request pass through for the default document, which is causing the module to fail. We look at the request (from Facebook) to retrieve and validate the user accessing our app. The initial request authenticates fine, but then I see a second request, which lacks the posted form variables, and thus causes authentication to fail.
In integrated pipeline mode, an http request for "/" yields 2 AuthenticateRequests in a row:
A request where AppRelativeCurrentExecutionFilePath = "~/"
A request where AppRelativeCurrentExecutionFilePath = "~/default.aspx"
That second request loses all of the form values, so it fails to authenticate. In classic mode, that second request is the only one that happens, and it preserves the form values.
Any ideas what's going on here?
UPDATE: Here is an image of the trace from module notifications in IIS. Note that my module, FBAuth, is seeing AUTHENTICATE_REQUEST multiple times (I'd expect 2 - one for authenticate and one for postauthenticate, but I get 4).
I'm starting to believe this has something to do with module/filter configuration because I've found a (Vista) box running the same code that doesn't fire these events repeatedly - it behaves as expected. I'm working through trying to figure out what the difference could be...
Thanks!
Tom
My solution was to add the following code at the end of Application_BeginRequest:
if (Request.RawUrl.TrimEnd('/') == HostingEnvironment.ApplicationVirtualPath.TrimEnd('/'))
Server.Transfer(Request.RawUrl+"Default.aspx", true);
DefaultHttpHandler is not supported,
so applications relying on sub-classes
of DefaultHttpHandler will not be able
to serve requests If your application
uses DefaultHttpHandler or handlers
that derive from DefaultHttpHandler,
it will not function correctly. In
Integrated mode, handlers derived from
DefaultHttpHandler will not be able to
pass the request back to IIS for
processing, and instead serve the
requested resource as a static file.
Integrated mode allows ASP.NET modules
to run for all requests without
requiring the use of
DefaultHttpHandler. Workaround
Change your application to use
modules to perform request processing
for all requests, instead of using
wildcard mapping to map ASP.NET to all
requests and then using
DefaultHttpHandler derived handlers to
pass the request back to IIS.
Hmmm, or this could be the issue.
ASP.NET modules in early request
processing stages will see requests
that previously may have been rejected
by IIS prior to entering ASP.NET,
which includes modules running in
BeginRequest seeing anonymous requests
for resources that require
authentication ASP.NET modules can run
in any pipeline stages that are
available to native IIS modules.
Because of this, requests that
previously may have been rejected in
the authentication stage (such as
anonymous requests for resources that
require authentication) or other
stages prior to entering ASP.NET may
run ASP.NET modules. This behavior is
by design in order to enable ASP.NET
modules to extend IIS in all request
processing stages. Workaround
Change application code to avoid
any application-specific problems that
arise from seeing requests that may be
rejected later on during request
processing. This may involve changing
modules to subscribe to pipeline
events that are raised later during
request processing.
http://learn.iis.net/page.aspx/381/aspnet-20-breaking-changes-on-iis-70/

Resources