PilotBob
PilotBob

Reputation: 3117

How do I send a 401 response from an HttpHandler?

We have a Login enforcement app which only allows a user to be logged into a single session in our app. This is done in the postauthenticate request event handler.

If the user needs to be logged out (they have another session) we do:

FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();

This has worked fine for a long time. Now we are adding a web api to our app. When you hit a web api Url the PostAuthentication event does fire, it sees the user has logged in elsewhere... however, it does a redirect to login.. well that's expected due to the code.

I attempted to change the code above to set the Response.StatusCode = 401 and then end the request. Well, that works fine, but asp.net is being "nice" and auto redirecting to the login page.

Is there a way I can respond with a 401 and not have it redirect to the login page if this request came from web api URL?

Upvotes: 1

Views: 1088

Answers (2)

be4i
be4i

Reputation: 47

You can set SuppressFormsAuthenticationRedirect of the HttpResponse to true and the FormsAuthentication module will not catch the 401.

Upvotes: 1

Travis Illig
Travis Illig

Reputation: 23894

The problem is that the FormsAuthenticationModule catches all outbound requests at EndRequest and if the status is 401 AND the URL isn't the configured login location, you get redirected to the login location.

There's not any great way to fix that. Basically I've seen two ways, neither of which are awesome:

  1. Implement your own FormsAuthenticationModule. Rather than use the out-of-the-box one, roll your own that knows about the exceptions and lets the 401 through.
  2. Add some logic to the login page that issues the 401 for you. Look at the inbound URL. If the URL is one of the redirects from the FormsAuthenticationModule but the user is already logged in, issue a 401 rather than displaying the login form. The FormsAuthModule won't do a circular redirect to the login form, so you're OK.

Upvotes: 1

Related Questions