Actually, this not works. It looks OK because of the cache of client. There is no way to do this as I know.
I got a case recently to build a site in IIS 8.5:
- When the visitor is logged on to the desktop with domain account, use this account for this website.
- When the visitor is not using domain account, do not pop up a login window asking for domain account, redirecting to a version for anonymous instead.
I thought it’s simple in IIS setting but I was wrong. The anonymous cannot work parallelly with Windows authentication.
After some digging in Google, I started my test:
- Deploy the site by using anonymous authentication.
- Select the login page for detecting domain user and change that page to Windows authentication instead of anonymous model.
- Add a custom page for this page on error 401. Model is set to “Execute a URL on this site”.
It works good but…
When the login page opened, it should contain a Url as parameter for returning back to the original page. So I have to deal it in the customized 401 page. I turned that page to an ashx with the command context.Response.Redirect. The URL for returning can be cut from context.Request.RawUrl.
After that, it went wrong. Form the same server which has the IIS installed, it still works well. But when I try this page on another computer, it will always redirect to the anonymous version page no matter it’s from the desktop logged with domain account or not. I’m sure that the site is added as Intranet zone and automatically logon is set in this zone.
Checked by network monitor, the browser will not get the 401 response in this scenario. As the ashx file request, only the 302 code is returned. That’s the reason why the browser won’t be notified to logon with the current user.
The solution is: if you want to use ashx with redirect function as a customized 401 page still, do not use context.Response.Redirect. Instead, try to do that with an HTML function with the 401 code in HTTP response.
context.Response.Status = "401 Unauthorized";
context.Response.StatusCode = 401;
context.Response.ContentType = "text/html";
<meta http-equiv=""refresh"" content=""0; url=" + redirectUrl + @""" />
It works like a charm.
I guess (yes, guess) when the browser get a 401 response first time, it will retry to the previous submitting/navigation with the domain account for login. If it’s failed again, it will pop up a login window after the html page is displayed. So as I required in HTML code, after it navigate to another page, the browser has no chance to display the login window. That’s the deal.
All I’m sure is it really works well. Hope it useful to you.