Custom 401 unauthorized error page

Sources: 1) ErrorCodeDemo1-GitHub , 2) ErrorCodeDemo2-GitHub

Quite often I see developers ignoring proper error redirection for 401 unauthorized access scenarios. The usual behaviour is to put an enterprise/application role constraint for the homepage and relying on the J2EE container to deliver the default error page. Not only does it look ugly, but it also breaks the application flow, as the end user has no other option provided to rectify the error.

This article talks about two simple approaches to display our own error page when an unauthorized user accesses your application. The end-result would be displaying something like this:

Approach 1: Declarative

This is a simple, one-step approach. You just define a reference to your own error page inside web.xml file, which gets called for a 401 error code.

Approach 2: Programmatic

The second approach is slightly elaborate. But effectively, there is no difference in the end-result. In this approach, I create a task-flow which checks for authorization from the security-context runtime object via a router, and then routes the user to either an error view or an appropriate application view.

In this case, both the auth-check task-flow and home.jspx need to be granted access to authenticated-role. This implies that all users with a valid username and password should be able to view this page and task-flow. It is the task-flow which then redirects the user to the appropriate view.

If authorization check is the only requirement, the approach 1 (web.xml configuration) should be sufficient. But if your application more logic to be implemented, beyond a security group check, then approach 2 would be a better fit.