IT Nota

  • Home
  • How To
  • .NET
  • WordPress
  • Contact

How to Customize 401 Error Page with 302 Redirect on IIS

Continuing from the last post on customizing 401 error page on IIS, there’s a different way to do so by using 302 Redirection.

Using this method is actually a bit more simple to do, it’s just that you have to create a second website with a landing page to serve as your error page. Not everyone has this privilege to just have a second instance created in production environment, so it’s always good to have more options.

When you need to restrict access to your web application on IIS, any unauthorized users will see the standard 401 Error Page from IIS:

401 – Unauthorized: Access is denied due to invalid credentials. You do not have permision to view this directory or page using the credentials that you supplied.

Server Error 401

Instead of serving a default 401 Error Page, it’s always good to show a customized 401 page that is more user-friendly. Here’s a one way to do it by using a page redirect.

Steps to Use Custom 401 Error Page using 302 Redirect in IIS

  1. Create an HTML page as our custom 401 page. In this example, it will be called ITNOTA-Custom-401.htm.

    Simple custom 401 error page in HTML

  2. Create an instance in IIS just for this file and set this file as the main landing page (or use it as your index.htm). For this example, we’ll set this up as fwd.itnota.com with a file name of ITNota-Custom-401.htm.

  3. Next, launch Internet Information Services (IIS) Manager and click on your site on the left pane.

  4. Click on Error Pages.

    IIS Site Error Pages Settings

  5. On the next screen, you will see a list of default error pages according to its Status Code. In this example, we want to select 401.

    IIS Site Error Page 401

  6. On the Edit Custom Error Page window, click on the Respond with a 302 redirect radio button and type in the URL of the second website where your custom 401 page resides, including the file name, then click OK.

    IIS Custom 401 Error Page using 302 Redirect

That’s all there is to it.

As a test, we can try to load the page and this is also where using 302 redirect is different than using a static page within the same instance. If using Windows Authentication, you will not see the Windows Security screen to enter your NTID and password. It does the authentication in the background and if you’re not authorized, you will right away be redirected to the second web page that hosts the 401 custom page.

IIS Render Custom 401 Error Page HTML

Yes, it’s almost like an anti-climax to see a plain custom 401 error page being displayed. I hope you can come up with a much better design than my example to make all the effort worthwhile.

This setting for a custom 401 using 302 redirect works for both ASP.NET and Classic ASP.

Further Reading

How to Use Custom 401 Error Page on IIS
How to Fix Access Denied (401) Error in Microsoft IIS

June 30, 2021 Filed Under: How To Tagged With: IIS, Internet Information Services, Microsoft, Windows Server

How to Use Custom 401 Error Page on IIS

When you need to restrict access to your web application on IIS, any unauthorized users will see the standard 401 Error Page from IIS:

401 – Unauthorized: Access is denied due to invalid credentials. You do not have permision to view this directory or page using the credentials that you supplied.

Server Error 401

Often times, though, you want to show your end users a custom error page with specific instructions on what to do. That is certainly a more graceful way of handling the error than just showing the standard windows 401 error page.

If you have the flexibility to setup your own web instances, you might want to try using 302 Redirect instead as it’s much simpler to setup. Otherwise, this is also a viable option, although a bit long.

Steps to Use Custom 401 Error Page in IIS

  1. Create an HTML page as our custom 401 page. In this example, it will be called ITNOTA-Custom-401.htm.

    Simple custom 401 error page in HTML

    For simplicity, we’ll save the file in C:\Temp folder.

  2. Next, launch Internet Information Services (IIS) Manager and click on your site on the left pane.

  3. Click on Error Pages.

    IIS Site Error Pages Settings

  4. On the next screen, you will see a list of default error pages according to its Status Code. In this example, we want to select 401.

    IIS Site Error Page 401

  5. On the Edit Custom Error Page window, click on the Set… button.

    IIS Edit Custom Error Page

  6. Under Set Localized Custom Error Path window, type in the location where the custom 401 HTML page resides in the Directory path box. Only type in the path/folder. The file name itself should be in the Relative file path textbox, then click OK.

    Set localized Custom Error Path in IIS

  7. You should see something similar to this. Click OK again.

    Edit Custom Error Page file path

  8. At this point, we’re done setting up the custom 401 error page. However, unless if you still use the default for other settings, you may run into this error:

            HTTP Error 500.19 – Internal Server Error
            Absolute physical path "c:\temp" is not allowed in system.webServer/httpErrors section in web.config file. Use relative path instead.
            

    IIS Internal Server Error 500.19

    If you read the error message, it points exactly at the problem in the configuration, that is in the system.webServer/httpErrors section.

  9. In IIS Manager, click on the server on the left navigation pane and click on Configuration Editor

    IIS Configuration Editor - Server level

  10. In the Configuration Editor, under Section:, click on the drop-down and select system.webServer, then httpErrors.

    IIS Configuration Editor system.webServer/httpErrors

  11. Click on allowAbsolutePathsWhenDelegated, then click on the Unlock Attribute if it’s locked. If it’s already unlocked (no padlock sign), then you’re good. Then click Apply under Actions.

    IIS Configuration Editor allowAbsolutePathsWhenDelegated unlocked

  12. Now, click on your site on the left pane of navigation, and also click on Configuration Editor.

    IIS site-level Configuration Editor

  13. Repeat the step to get to the system.webServer/httpErrors and set allowAbsolutePathsWhenDelegated to True. Then, click Apply.

    IIS Configuration Editor allowAbsolutePathsWhenDelegated set to True

  14. At this point, depending on your Authentication setting, you should be able to see the custom 401 error page in your browser (if you failed to authenticate). However, if you use Windows Authentication, you might see a 401.2 error page.

            HTTP Error 401.2 - UnauthorizedYou are not authorized to view this page due to invalid authentication headers.
            

    IIS Error 401.2 - Unauthorized

    Rest easy, we just need to redirect this 401.2 error to our custom 401 error page.

  15. Go back to Internet Information Services (IIS) Manager and click on your site on the left
    and Error Pages on the right.

    IIS Site Error Pages Settings

  16. This time, we create an additional entry for 401.2 error by clicking on the Add… link under Actions on the right pane. You can duplicate the entry for 401 setup, except this time the Status code should have a value of 401.2. Click OK.

    IIS Site edit Custom Error Page for 401.2 error

  17. Now you should see the list in your Error Pages windows similar to this.

    List of error pages codes in IIS

That’s all there is to it.

As a test, we can try to load the page and when prompted to type in the a credential, you can leave it blank and click the Cancel button.

Microsoft Edge Windows Security screen

If you purposely fail the authentication to access your test website, you should see your custom 401 error page is displayed in your browser now.

IIS Render Custom 401 Error Page HTML

Yes, it’s almost like an anti-climax to see a plain custom 401 error page being displayed. I hope you can come up with a much better design than my example to make all the effort worthwhile.

If you go to your web folder, you will see a web.config file, and your configuration is saved there:

  <httpErrors allowAbsolutePathsWhenDelegated="true">
    <remove statusCode="401" subStatusCode="-1" />
    <error statusCode="401" prefixLanguageFilePath="c:\temp" path="ITNOTA-Custom-401.htm" responseMode="File" />
    <error statusCode="401" subStatusCode="2" prefixLanguageFilePath="c:\temp" path="ITNOTA-Custom-401.htm" responseMode="File" />
  </httpErrors>
</system.webServer>

IIS Custom 401 configuration in web.config

This setting for a custom 401 works for both ASP.NET and Classic ASP.

Further Reading

How to Customize 401 Error Page with 302 Redirect on IIS
How to Fix Access Denied (401) Error in Microsoft IIS
Custom 401 page in IIS with ASP.NET
Error: Vault Pre-check fails on TestASPNet.aspx – IIS shows absolute physical path is not allowed
500.19 error in IIS7 when an error occurs

June 28, 2021 Filed Under: How To Tagged With: IIS, Internet Information Services, Microsoft, Windows Server

How to Enable Secure HttpOnly Cookies in IIS

Session cookies are often seen as one of the biggest problems for security and privacy with HTTP, yet often times, it’s necessary to utilize it to maintain state in modern web applications. By default, it is insecure and vulnerable to be intercepted by an authorized party.

Cookies typically store session identifiers that may offer full access to an account, therefore if a cookie is intercepted, a session can be hijacked by someone who is not the real user but pretending as that user.

For this reason, it’s very important that we need to set parameters on how the cookies are passed and have it encrypted as they get sent/read between a web server and the browser.

In order to make cookies more secure to use, there are two things we need to pay attention to, they are HttpOnly and Secure flags.

HttpOnly Flag

The first flag we need to set up is HttpOnly flag. By default, when there’s no restriction in place, cookies can be transferred not only by HTTP, but any JavaScript files loaded on a page can also access the cookies. This ability can be dangerous because it makes the page vulnerable to cross-site scripting (XSS) attack.

The only way to restrict this is by setting HttpOnly flag, which means the only way cookies are sent is via HTTP connection, not directly through other means (i.e., JavaScript).

Secure Flag

The second flag we need to pay attention to is Secure flag. This flag highlights the second issue that by default cookies are always sent on both HTTP and HTTPS requests. A malicious attacker who can’t see encrypted traffic with HTTPS connection can easily switch to HTTP connection and access the same cookie because it is not encrypted. Therefore, we need to set the Secure flag to ensure that the cookie in encrypted when it’s created.

Enable HttpOnly Flag in IIS

Edit the web.config file of your web application and add the following:

<system.web>
  ...
  <httpCookies httpOnlyCookies="true" requireSSL="true" />
  ...
</system.web>

Enable Secure Flag in IIS

To enable secure flag in IIS, it is better to use URL Rewrite and add the following to your web.config file:

<system.webServer>
  <rewrite>
    <outboundRules>
      <rule name="Use only secure cookies" preCondition="Unsecured cookie">
        <match serverVariable="RESPONSE_SET_COOKIE" pattern=".*" negate="false" />
        <action type="Rewrite" value="{R:0}; secure" />
      </rule>
      <preConditions>
        <preCondition name="Unsecured cookie">
          <add input="{RESPONSE_SET_COOKIE}" pattern="." />
          <add input="{RESPONSE_SET_COOKIE}" pattern="; secure" negate="true" />
        </preCondition>
      </preConditions>
    </outboundRules>
  </rewrite>
...
</system.webServer>

Check Flags Settings

This example demonstrates an ASP.NET website that has HttpOnly flag set, but not the Secure flag using a professional web scan tool.

Scan result for cookie with missing secure flag

The scanner did not detect secure flag in the HTTP header with the following explanations:

Cookie Missing ‘Secure’ Flag

Description

The session ID does not have the ‘Secure’ attribute set. This attribute prevents cookies from being seen in plaintext. It may be possible for a malicious actor to steal cookie data and perform session theft through man-in-the-middle (MITM) or traffic sniffing attacks. The exploitable condition exists for unencrypted cookies to be passed over the network if a user accesses the site through HTTP instead of HTTPS, or if a link to a resource such as an image file or CSS file within the specified domain uses the HTTP protocol.

Risk

Data may be exposed to unauthorized parties during cookie transmission and increases the risk of session theft via man-in-the-middle (MITM) or traffic sniffing attacks.

Recommendation

Change the default ‘Secure’ attribute from FALSE to TRUE to ensure cookies are sent only via HTTPS. The ‘Secure’ attribute should be set on each cookie to prevent cookies from being observed by malicious actors. Implement the ‘Secure’ attribute when using the Set-Cookie parameter during authenticated sessions.

After applying the recommended configuration mentioned above, the scan result is good as shown below.

Scan result after secure flag is activated for cookie

As you may have noticed, in this particular example, the Session Cookie Missing ‘HttpOnly’ Flag was already fixed.

Checking the header using cURL:

$ curl -I https://www.itnota.com

Before

HTTP/1.1 200 OK
Cache-Control: private, no-store, max-age=0, s-maxage=0
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Vary: Accept-Encoding
Server: Microsoft-IIS/8.5
Set-Cookie: ASP.NET_SessionId=o42zbtr1rzzje3wlvwwcnjmv; path=/; HttpOnly
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
X-Frame-Options: SAMEORIGIN
Date: Tue, 10 Jul 2018 20:42:03 GMT
Content-Length: 6722

After

HTTP/1.1 200 OK
Cache-Control: private, no-store, max-age=0, s-maxage=0
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Vary: Accept-Encoding
Server: Microsoft-IIS/8.5
Set-Cookie: ASP.NET_SessionId=bhn5qcmggcxdy34g5d4kp3hk; path=/; HttpOnly; secure
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
X-Frame-Options: SAMEORIGIN
Date: Tue, 10 Jul 2018 20:46:38 GMT
Content-Length: 6722

Notice the word secure after the HttpOnly at the end of the line of Set-Cookie HTTP header.

Emphasis

Set-Cookie: ASP.NET_SessionId=bhn5qcmggcxdy34g5d4kp3hk; path=/; HttpOnly; secure

Buy me a coffee?

Buy me a coffee If you find this post helpful and would like to buy me a coffee to support the work here, you’ll have our big thanks!
Support IT Nota: Buy me a Coffee

Download

URL Rewrite

Further Reading

HTTP/2 in Action
The Secure Attribute
The HttpOnly Attribute
httpCookies Element (ASP.NET Settings Schema)
Ensuring secure cookies with URL Rewrite
How to Setup HTTP Strict Transport Security (HSTS) on IIS

May 2, 2019 Filed Under: How To Tagged With: IIS, Information Security, Internet, Internet Information Services

How to Import IIS Log to PostgreSQL

If you ever had a need to dump and analyze IIS logs from a database, this post will show you how to do it in PostgreSQL RDBMS.

The assumption is that you’re already familiar with the default installation and setup of PostgreSQL, if not please check the manual link at the bottom of this post. We will use default settings.

Steps to Create IIS Log Table and Import Log File to PostgreSQL

  1. Create a database called mydb.

  2. We need to prepare a table that matches the fields from IIS log, so we need to create a table called iislog by running the following SQL:

    CREATE TABLE public.iislog
    (
        date date,
        "time" time without time zone,
        sip character varying(48) COLLATE pg_catalog."default",
        csmethod character varying(8) COLLATE pg_catalog."default",
        csuristem character varying(255) COLLATE pg_catalog."default",
        csuriquery character varying(2048) COLLATE pg_catalog."default",
        sport character varying(4) COLLATE pg_catalog."default",
        susername character varying(256) COLLATE pg_catalog."default",
        cip character varying(48) COLLATE pg_catalog."default",
        csuseragent character varying(1024) COLLATE pg_catalog."default",
        csreferer character varying(4096) COLLATE pg_catalog."default",
        scstatus integer,
        scsubstatus integer,
        scwin32status bigint,
        timetaken integer
    )
    WITH (
        OIDS = FALSE
    )
    TABLESPACE pg_default;
    
    ALTER TABLE public.iislog
        OWNER to postgres;
    
  3. Go to the location of where the IIS log files are stored. By default, the location is in the following folder:

    %SystemDrive%\inetpub\logs\LogFiles
    

    However, as the best practice, most enterprise applications will have a different location on a different drive for log. In this example, we’ll use C:\Temp\IISLogs\ folder.

  4. We will certainly not going to import each log file one-by-one to the database, so the best thing to do before we do the import is to combine all the log files we want to analyze. Just for the sake of simplicity for this demonstration, we want to include all log files within this folder and combine them into one big log file. We can do this by opening either a Command Prompt or PowerShell Windows. It doesn’t matter which one you prefer, it will work the same way.

  5. In the Command Prompt or PowerShell Window, make sure you’re in the IIS log folder and type in the following command:

    Command only

    type *.log > filename.log
    

    Command with prompt (as in this example)

    C:\Temp\IISLog> type *.log > combinedLogs.log
    

    *The prompt is included to show that you need to be in your IIS log folder to execute this operation.

  6. Now we need to massage the combined log file a bit before we can import it within one operation.

    If you open the new log file (combinedLogs.log) with a text editor, you will see all the headers from every single log file were included as well and it looks something similar to this:

    #Software: Microsoft Internet Information Services 10.0
    #Version: 1.0
    #Date: 2018-08-02 15:08:58
    #Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken
    
  7. By using a text editor such as Sublime Text, we can clean up this log file by using Regex Find and Replace.

    From the top menu, go to Find and Replace… (CTRL-H in Windows) and make sure the Regex option is activated and type (or copy and paste) the following search string in the Find: box:

    #Software: Microsoft Internet Information Services 10.0\n#Version: 1.0\n#Date: [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\n#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs\(User-Agent\) cs\(Referer\) sc-status sc-substatus sc-win32-status time-taken\n
    

    Remove IIS Log headers using Regex Find and Replace

  8. Press Replace All button to remove all instances of those headers and re-save the file.

  9. Now we will import this log file by using COPY command.

    Go back to PostgreSQL shell and type in the following:

    COPY public.iislog FROM 'c:\temp\iislogs\combinedLogs.log' DELIMITER ' ';
    

    *If you use a different table name and location of IIS log, make sure you change it to match yours.

That’s all there is, now you should be able to query the log and slice and dice the data however you need it.

Caveat

Important: If you have a rather big combined log file (even only a few MB in size), make sure you do the import from the command line. Do not use pgAdmin web interface as it may not be able to handle the load.

Further Reading

PostgreSQL Manuals

Download

PostgreSQL

March 20, 2019 Filed Under: How To Tagged With: IIS, Internet Information Services, PostgreSQL, SQL

How to Backup IIS Manager Connections List on Windows

You’ve been using IIS Manager to manage remote IIS from your local computer. But how do you export the connections list if you move to a new computer or just to back it up if you lost all data?

IIS Manager Connect Remote Server

This post will show you how you can export and back up IIS Manager connections list on your local PC.

All connections in IIS Manager are saved in a binary file called InetMgr.preferences and it can be found in the following folder:

%APPDATA%\Microsoft\WebManagement\7.0.0.0

Or

C:\Users\{NTID}\AppData\Roaming\Microsoft\WebManagement\7.0.0.0

*Replace the {NTID} with the user id you use to logon to your computer.

IIS Manager preferences file

This is the file you want to backup so copy this file to your backup folder. When you need to restore it, just copy this file back to the above folder and you should be back in business.

Important: Do not try to restore the file when IIS Manager is open. When you quit the application, it will write the last settings on that InetMgr.preferences file.

Further Reading

How to Manage IIS Servers Remotely

March 6, 2019 Filed Under: How To Tagged With: IIS, Internet Information Services, Microsoft, Windows, Windows 10

« Previous Page
Next Page »
Buy me a coffee Support this site
Buy Me a Coffee?

Categories

  • .NET
  • Coding
  • Cybersecurity
  • Database
  • How To
  • Internet
  • Multimedia
  • Photography
  • Programming
  • Resources
  • Review
  • Tips and Tricks
  • Uncategorized
  • Use Case
  • WordPress
  • Writing

Recent Posts

  • How to View Stored Procedure Code in SQL Server
  • How to Find a String in SQL Server Stored Procedures
  • How to Remove Cached Credentials without Rebooting Windows
  • ESP Work Automation: Empowering Enterprises with Streamlined Workflows and Operational Efficiency
  • How to Search for a String in All Tables in a Database

Recent Posts

  • How to View Stored Procedure Code in SQL Server
  • How to Find a String in SQL Server Stored Procedures
  • How to Remove Cached Credentials without Rebooting Windows
  • ESP Work Automation: Empowering Enterprises with Streamlined Workflows and Operational Efficiency
  • How to Search for a String in All Tables in a Database

Tags

.NET .NET Core AdSense ASP.NET Cdonts Dll Classic ASP Code Editor ETL FSharp Genesis Framework Git Google HP Asset Manager HTML5 Hugo IIS Information Security Internet Internet Information Services iOS JAMStack Linux macOS Microsoft Microsoft SQL Server MVC PHP PowerShell Python Simple Mail Transfer Protocol Smtp Server SQL SQL Server SSIS SSMS SSRS Sublime Text Visual Studio Visual Studio Code VPN Windows Windows 8 Windows 10 Windows 2012 Windows Server

Copyright © 2011-2025 IT Nota. All rights reserved. Terms of Use | Privacy Policy | Disclosure